Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert iterator to int

int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;

I'm trying to find index of an element in vector. It's ok with iterators, but I want it as int. How can I do it?

like image 302
thetux4 Avatar asked May 26 '11 09:05

thetux4


People also ask

How do I assign an iterator in C++?

Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements). To assign the value of the element the iterator is pointing at, dereference the iterator first, then use the assign operator.


2 Answers

You can use std::distance for this.

i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );

You will probably want to check that your index isn't out of bounds, though.

if( i == names.size() )
    // index out of bounds!

It's probably clearer to do this with the iterator before using std::distance, though.

std::vector<std::string>::iterator it = std::find( names.begin(), names.end(), s );

if( it == names.end() )
     // not found - abort!

// otherwise...
i = std::distance( names.begin(), it );
like image 98
CB Bailey Avatar answered Oct 19 '22 23:10

CB Bailey


std::vector<string>::iterator it = std::find(names.begin(), names.end(), s);
if (it != names.end()) {
    std::cout << std::distance(names.begin(), it);
} else {
    // ... not found
}
like image 44
Georg Fritzsche Avatar answered Oct 19 '22 23:10

Georg Fritzsche