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