【问题标题】:C++ function code, using arraysC++ 函数代码,使用数组
【发布时间】:2015-07-17 07:42:25
【问题描述】:

我无法理解解决此问题的代码有什么问题。任何帮助,将不胜感激。

在一个或多个等于目标的连续字符串中查找最早出现的字符串;将开始设置为目标第一次出现的位置,将结束设置为该最早连续序列中目标的最后一次出现,并返回真。如果 n 为负数或 a 中没有字符串等于 target,则 begin 和 end 保持不变并返回 false。

bool locateSequence(const string a[], int n, string target, int& begin, int& end)
{
    if (n < 0)
        return 0;
    for (int i=0; i < n-1; i++)
    {
        if (a[i]==target && a[i+1]==target )
        {
            begin = i;
            break;
        }
    }
    for (int f=0; f < n-1; f++)
    {
        if (a[f]==target && a[f+1]==target )
        {
            end = f + 1;
            return true;
        }
    }
    return false;
}

【问题讨论】:

  • 什么是错误(编译,错误结果,...)?输入,预期输出?
  • 顺便说一句,-1 不是 bool
  • 您的函数旨在返回一个布尔值,因此通过在第 nr.4 行 if (n&lt;0) return -1 返回 -1 肯定会引发错误。
  • @Ange1:嗯,实际上将bool 设置为-1 是有效的。没有任何错误。但是,由于它不是 0,它解析为 true,这可能不是 OP 的意图......
  • 我更愿意将n 声明为unsigned int,而不是通过检查if (n &lt; 0) 丢弃一半可能的值。

标签: c++ arrays function


【解决方案1】:

您正在尝试编写已经免费提供的东西!

请看一下:

std::search Search range for subsequence 

例子:

#include <iostream>
#include <algorithm>

std::string search_in("abcdefhalloxyz");
std::string search_for("hallo");


int main()
{
    std::string::iterator it =
        std::search
        (
         search_in.begin(), search_in.end(),
         search_for.begin(), search_for.end()
        );

    if ( it != search_in.end() )
    {
        std::cout << "Found at " << it-search_in.begin() << std::endl;
    }

}

【讨论】:

  • 这很好,但我正在尝试使用函数 bool locateSequence(const string a[], int n, string target, int& begin, int& end) 因为这是问题的一部分。跨度>
猜你喜欢
  • 2014-06-09
  • 2013-05-26
  • 1970-01-01
  • 2012-05-05
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多