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?
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.
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 );
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With