• Advertisement
Sign in to follow this  

[C++] iterator to index

This topic is 2977 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi all, I'm using std::find on a std::vector, this returns the iterator but I need the index of the returned iterator. if I'm not mistaking C# has a build in function for this (indexof()) but I need this in c++. is there a quick easy way to know this ? or do I have just have to loop though the vector , compaire it to the iterator and if equal return the loop index ? cheers

Share this post


Link to post
Share on other sites
Advertisement
It's worth pointing out there are various kind of iterators, std::vector's iterator is random access iterator so binary - operator is defined but if you want to keep your code generic then use visitor's solution, std::distance, this function is specialized for different kinds of iterator and will pick the most optimal method (like with random access iteartors it can use binary - operator).

Share this post


Link to post
Share on other sites
Also, std::vector<T>::iterator is a Random Access Iterator, so you can do this with it:

size_t index = findResultIter - vec.begin();

EDIT: Never mind, what snk_kid said :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement