Reputation: 301
I'm iterating through a map, that map value type is vector. I'm getting vectors in the map one by one and searching for a item using std::find() method.
for(BoundWaysMap::const_iterator iterator = boundWays.begin(); iterator != boundWays.end(); iterator++)
{
string wayId = iterator->first;
std::vector<string> nodesRefCollection = iterator->second;
if(std::find(nodesRefCollection.begin(), nodesRefCollection.end(), id)!=nodesRefCollection.end())
{
std::string cont = "|" + wayId;
legsFrame.append(cont);
legsCount ++;
isFound = true;
}
}
I want to get the index of the found item form the find method.
Upvotes: 6
Views: 12476
Reputation: 151
You can keep the iterator returned by the find function like so:
std::vector<string>::iterator iter = std::find(nodesRefCollection.begin(), nodesRefCollection.end(), id);
if( iter != nodesRefCollection.end() )
{
int index = std::distance(nodesRefCollection.begin(), iter);
std::string cont = "|" + wayId;
legsFrame.append(cont);
legsCount ++;
isFound = true;
}
Upvotes: 5
Reputation: 227370
Save the iterator returned by std::find
, and then use std::distance
:
auto it = std::find(nodesRefCollection.begin(), nodesRefCollection.end(), id);
if (it != nodesRefCollection.end())
{
auto idx = std::distance(nodesRefCollection.begin(), it);
}
Note that a vector's iterators also allow you to use the -
operator:
auto idx = it - nodesRefCollection.begin();
Upvotes: 2
Reputation: 76240
std::find
returns an iterator to the found value, so you can get the index by using std::distance
on that iterator:
std::distance(nodesRefCollection.begin(), std::find(...));
Upvotes: 10