c++ - 在数组搜索中返回迭代器索引

标签 c++ arrays iterator

我想搜索特定数字并让迭代器跟踪正在测试的数组元素。如果找到该数字,我想返回找到该数字的数组的索引。这是我到目前为止所拥有的:

    vector<int>::iterator iterator;
    find(vector.begin(),vector.end(), num);

    if(//the number is found in the search)
    {
       return //where the number is found
    }

我不太确定如何将迭代器与正在测试的数组元素同步。如果可能的话,我将不胜感激解决此问题的任何帮助。

最佳答案

这应该做你想做的:

std::vector<int> v = {500, 600, 700};
auto it = std::find(v.begin(),v.end(), 600);
std::size_t pos = it - v.begin(); //found(iterator) - begin(iterator)

// of course first you should check if (it != v.end())

关于c++ - 在数组搜索中返回迭代器索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258755/

相关文章:

c++ - map 实现中的列表迭代器实现 - 麻烦

c++ - 如何检测我是否正在使用特定的 Visual Studio 版本编译代码?

c++ - 使用鼠标移动qwidget而不超出父级大小

c++ - 为什么在另一个文件中更改 extern const 时链接器不会失败?

c++ - 带有自定义类指针的优先级队列断言错误

php - 如何在表单值中存储sql列名

java - 使用移位运算符理解 java 数组初始化

c++ - 使用 vector 迭代器时出现 EXC_BAD_ACCESS?

c++ - operator<< 不能使用其 friend 数组的 IT 成员

javascript - 合并嵌套数组并删除重复项