字符串数组到 C++ 函数

String array to C++ function

我想检查给定名称是否在可能名称数组中。我写了这个小调试功能(是的......我知道它总是 return true )试图理解为什么它不起作用以及为什么我得到以下错误。

代码

char[] people_names = ["Mario","Luigi"];

bool lookupTerm (string term, string possible_names[]){
   for(const string &possible_name : possible_names)
     cout << possible_name <<  endl;

    return true;
}

错误

jdoodle.cpp: In function 'bool lookupTerm(std::__cxx11::string, std::__cxx11::string*)':
jdoodle.cpp:19:38: error: no matching function for call to 'begin(std::__cxx11::basic_string<char>*&)'

我知道这一定很明显,但根据我搜索的内容,它应该有效。有人能指出我正确的方向吗?

问题在于,当您将数组传递给函数时,它会衰减为指向其第一个元素的指针。

即使您尝试将参数声明为数组也没关系,编译器仍将其转换为指针。声明参数时,string possible_names[] 等于 string* possible_names

简单的解决方案是根据您的需要使用 std::vector or std::array 和 use-case.

使用 std::vector 你的代码看起来像这样:

std::vector<std::string> people_names = { "Mario", "Luigi" };

bool lookupTerm(const std::string& term, const std::vector<std::string>& possible_names) {
    for (const std::string &possible_name : possible_names)
    {
        if (possible_name == term)
            return true;
    }
    return false;
}

一行使用std::find:

bool lookupTerm(const std::string& term, const std::vector<std::string>& possible_names) {
    return std::find(possible_names.begin(), possible_names.end(), term) != possible_names.end();
}

如果性能成为问题,您可以通过使用排序向量来提高性能(使用 std::sort) and std::lower_bound:

//at one point:
std::sort(people_names.begin(), people_names.end());

bool lookupTerm(const std::string& term, const std::vector<std::string>& sorted_possible_names) {
    //sorted_possible_names must be always sorted when you call this!
    auto i = std::lower_bound(sorted_possible_names.begin(), sorted_possible_names.end(), term);
    return (i != sorted_possible_names.end() && *i == term);
}