String array to C++ function

孤街浪徒 提交于 2020-01-24 23:10:48

问题


I want to check if a given name is inside an array of possible names. I wrote this small debugging function ( yeah... I know it always return true ) trying to understand why it does not work and why I get the below error.

Code

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;
}

Error

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>*&)'

I know that it must be really obvious but according to what I have searched for, it should work. Can someone point me in the right direction?


回答1:


The problem is that when you pass an array to a function, it decays to a pointer to its first element.

It doesn't matter if you attempt to declare the argument as an array, the compiler still translates it as a pointer. string possible_names[] is equal to string* possible_names when you declare arguments.

The simple solution is to use either std::vector or std::array depending on your needs and use-case.

Using std::vector your code would look something like this:

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;
}

One line using 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();
}

If performance becomes a problem you can increase the performance of this by using a sorted vector (using 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);
}


来源:https://stackoverflow.com/questions/49410992/string-array-to-c-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!