问题
I am looking for an element in a C++ vector, and when I find it, I want to get found element's index in a numerical form(integer, float).
My naive attempt is this :
int x;
int index;
vector<int> myvector;
vector<int>::iterator it;
it = find(myvector.begin(), myvector.end(), x);
index = (int) * it;
This code is giving error. Can you tell me how I can convert iterator to int(if possible), or can you tell me how I can get found element's index in other way? Thanks.
回答1:
You need to use standard function std::distance
index = std::distance( myvector.begin(), it );
if ( index < myvector.size() )
{
// do something with the vector element with that index
}
Try always to use std::distance even with random access iterators. This function is available in the new and old C++ Standards.
回答2:
If you want the index of the found element, then that's the distance from the start of the sequence:
index = it - myvector.begin();
or, since C++11,
index = std::distance(myvector.begin(), it);
which will work with any forward iterator type, not just random-access ones like those from a vector.
回答3:
You just dereference the iterator like this
index = *it;
However you should first see if you actually found something
it = find(myvector.begin(), myvector.end(), x);
if (it != myvector.end())
{
index = *it;
}
To find the index in that the match was found, you can use subtraction of the found pointer from the start of the vector.
it = find(myvector.begin(), myvector.end(), x);
if (it != myvector.end())
{
index = it - myvector.begin(); // Index from start of vector
}
Also, hopefully in your actual code you defined x, as in the snippet you showed x is uninitialized so this will result in undefined behavior.
来源:https://stackoverflow.com/questions/26995725/how-to-convert-vector-iterator-to-int-in-c