c++ - 查找 vector 中的值索引位置

标签 c++ vector

我正在使用此代码查找数组中搜索值的索引。我收到一个错误,这与常量 vector 有关,但我不知道如何修复它。

int linearFind( const vector<int>& vec, int y){
    vector<int>::iterator t=find(vec.begin(), vec.end(), y);
    if (t != vec.end())
        return (t-vec.begin());
    else
        return -1;
}

最佳答案

问题是,如vec传递为 const& ,其 begin 返回的迭代器和endstd::vector<int>::const_iterator s,不是std::vector<int>::iterator s。因此,find还将返回 std::vector<int>::const_iterator无法转换为 std::vector<int>iterator因为这会下降 const .

所以要解决这个问题,要么使用

std::vector<int>::const_iterator t = find(vec.begin(), vec.end(), y);

的,如果你使用C++11或更高版本,就更容易

auto t = find(vec.begin(), vec.end(), y);

关于c++ - 查找 vector 中的值索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35167251/

相关文章:

使用 vector::push_back() 方法时,C++ vector 编译错误

C++ 为基元调用 allocator.construct

c++ - 如何使 =NULL 在 SQLite 中工作?

c++ - 每次在 C++ 构建器中移动鼠标时绘制新行

c++ - 有没有办法阻止指针赋值?

c++ - 存储需要精确匹配和最接近匹配的值的最佳结构

C++最有效的方法迭代 vector 中的特定内容

c++ - 我在 C++ 中的继承和多态性上遇到了麻烦

c++ - 如何比较和存储 2 个 vector 位置的数据元素?

C++ std::vector<>::iterator 不是指针,为什么?