C++ vector : Function not viable + No matching function

标签 c++ vector

所以,似乎每次我尝试编译时,我都遇到了一个涉及的问题

“错误:没有匹配函数来调用‘search_and_report’”

   while(name!="!")
   {
      label = "linear_search";
      search_and_report(names,n,name,label,linear_search);

      label = "binary_search";
      search_and_report(names,n,name,label,binary_search);

      cout << "Search for name: (! when done): ";
      getline(cin,name);
   }

我怀疑是我对 vector 的初始化导致了问题。

{
   int n = 0;
   string label;
   string name;
   vector<string> names(n);

   // start program
   cout << "Enter a name (! when done): ";
   getline(cin,name);

   while(name!="!")
   {
      n++;
      names.push_back(name);
      cout << "Enter a name (! when done): ";
      getline(cin,name);
   }

我一直在阅读这个网站: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm 它说我应该被允许将我的 "n" 放在 push_back 中以允许它增长。但老实说,我不确定自己对 vector 的理解是否达到了应有的程度。

编辑 正如评论中提到的,我已经删除了外部代码,并且按照要求,我将提供函数签名。

void search_and_report(std::vector<const string> names[], int n, string name, string label,
                       bool (*search)(vector<const string> names[], int n, string name,
                                      int &count))

最佳答案

从您提供的链接中,函数的签名 search_and_report是:

void search_and_report(vector<const string> names[], int n, string name,
                       string label,
                       bool (*search)(vector<const string> names[], int n,
                                    string name, int &count));

第一个参数不是 vector ,是 vector 的数组

根据我读到的内容,您应该更改函数以获取 const std::vector<std::string>& (参见 binary_searchlinear_search 的签名)。

注意:使用 std::vector<const string>没有意义,因为 vector 处理它所持有的字符串对象的所有内存分配。我想你想用 const std::vector<std::string>&正如我上面写的。

更新:关于二分查找。

如果 vector 是有序的,你可以这样进行二分查找(伪代码):

bool binary_search(vector, str, begin, end) {
    int m = (end + begin) / 2;

    if (vector[m] < str) {
        return binary_search(begin, m-1);
    }

    if (vector[m] > str) {
        return binary_search(m+1, end);
    }

    return true;
}

关于C++ vector : Function not viable + No matching function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028240/

相关文章:

c++ - 为什么结构变量超出范围

c++ - 遍历字符串和 switch 语句 : C++

c++ - 我需要帮助来定位我的 malloc 错误

c++ - 当我们重载新运算符时,是否有必要重载放置新运算符?

excel - Matlab 数据预处理和动态结构分配

c++ - 在 c++/cli 中创建 .Net Excel::Application

r - 计算数据框行中的唯一元素并返回出现次数最多的元素

c++ - C++用仅两个零替换数组中的偶数个零

c++ - vector中cbegin和cend的使用

c++ - 没有运算符 >> 匹配这些操作数……为什么?