Question

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.

Was it helpful?

Solution 2

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;
  }

OTHER TIPS

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(...));

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top