从vector c++中获取匹配项的索引

Get index of the matching item from vector c++

本文关键字:索引 获取 vector c++      更新时间:2023-10-16

我正在迭代一个映射,该映射值类型是vector。我在地图中一个接一个地获得向量,并使用std::find()方法搜索项目。

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

我想从find方法中获得找到的项目的索引。

std::find返回找到的值的迭代器,因此您可以通过在该迭代器上使用std::distance来获得索引:

std::distance(nodesRefCollection.begin(), std::find(...));

可以这样保存find函数返回的迭代器:

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

保存std::find返回的迭代器,然后使用std::distance:

auto it = std::find(nodesRefCollection.begin(), nodesRefCollection.end(), id);
if (it != nodesRefCollection.end())
{
  auto idx = std::distance(nodesRefCollection.begin(), it);
}

注意,vector的迭代器也允许使用-操作符:

auto idx = it - nodesRefCollection.begin();