我是 C++ 的新手,正在尝试使用“Essential C++”一书中的一些示例。当我从书中写下这段代码时:
int *find(const vector<int> &vec, int value) { ... }
g++ 编译器给我一个错误:
error: invalid conversion from 'const int*' to 'int *' [-fpermissive]
我试着把它改成
const int *find(const vector<int> &vec, int value)
而且效果很好。
所以我只是想知道这是否有任何详细原因?谢谢!
这是书中的代码:
int* find(const vector<int> &vec, int value) {
for(int ix = 0; ix < vec.size(); ++ix)
{
if(vec[ix] == value)
return &vec[ix];
}
return 0;
}
最佳答案
我猜你正在做类似的事情
int *find(const vector<int> &vec, int value)
{
...
return &vec[someIndex];
}
你不能那样做,因为你传递的是一个 const
引用给 vector 。因此需要返回 const int*
。
你真正应该做的是使用 std::find
.
vector<int>::const_iterator i = std::find(vec.begin(), vec.end(), value);
// check if an element was found and print it out
if (i != vec.end()) std::cout << *i << std::endl;
这还有一个额外的好处,即当在 vector 中找不到值时,它不会产生未定义的行为。
关于c++ - 为什么 "int *find(const vector<int> &vec, int value)"会给我一个无效的转换错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17091832/