字符串数组到C ++函数 [英] String array to C++ function
问题描述
我想检查一个给定的名称是否在可能的名称数组内.我写了这个小的调试函数(是的,我知道它总是返回true),试图理解为什么它不起作用以及为什么出现以下错误.
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.
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>*&)'
我知道它必须确实很明显,但是根据我的搜索,它应该可以工作.有人可以指出我正确的方向吗?
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?
推荐答案
问题是,当您将数组传递给函数时,它会衰减为指向其第一个元素的指针.
The problem is that when you pass an array to a function, it decays to a pointer to its first element.
尝试将参数声明为数组并不重要,编译器仍会将其转换为指针.声明参数时,string possible_names[]
等于string* possible_names
.
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.
简单的解决方案是使用 std::vector
或 std::array
,具体取决于您的需求和用例.
The simple solution is to use either std::vector
or std::array
depending on your needs and use-case.
使用std::vector
您的代码应如下所示:
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;
}
使用 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::lower_bound
:
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);
}
这篇关于字符串数组到C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!