7

Why does the vector find return the iterator instead of the integer value?

vector<string>::iterator itr1 = std::find(words.begin(), words.end(), word);
0

1 Answer 1

12

std::find works for all sorts of containers, not just std::vector. For example, it works with std::list but that container does not allow accessing elements by index (at least not easily). For it to work with all kinds of containers it needs to return something all containers understand, an iterator.

Edit : If you want to find the index position equivalent to a given iterator, you can use std::distance. For example :

std::distance(std::begin(words), itr1);

This will work for standard containers but it may be slower for some. It returns the size of the container if the element is not found, since find returns end if it fails to find the element and the distance between begin and end is the size of the container.

Sign up to request clarification or add additional context in comments.

6 Comments

Is it possible to find all the indexes of occurrences of the word in the vector?
@Gani Yes, perform the search in a loop. Instead of searching from begin to end, replace begin by the iterator following the last one you found. I don't think the standard library has a function for that.
@Gani: Why do you want indices so badly? What's wrong with using iterators?
Iterators are the glue that holds containers and algorithms together. I've seen several 3rd party collection libraries, and none of them had iterators. They also didn't have algorithms because they (we) couldn't get them to work with enough containers without 'em.
@Gani It's the standard library, or std library. STL is something else and essentially unused anymore. What's the difference between “STL” and “C++ Standard Library”? Someone else already edited your question to reflect this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.