从vector c++中获取匹配项的索引
Get index of the matching item from vector c++
我正在迭代一个映射,该映射值类型是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();
相关文章:
- C++17:如何在并行 STL 中获取工作项的索引
- Direct3D 11 - HLSL - 获取顶点索引 ID
- 在 std::variant 中按类型获取索引
- CPtrList - 如何获取元素的索引?
- 根据字符获取数组的索引
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 获取结构 c++ 中元素的索引
- 是否可以将变体的索引作为 constexpr 变量获取?
- 如何使用值获取结构的索引
- 使用 Netlink 获取进程索引节点
- C++ 通过 std::transform 的 vector 索引获取向量
- 从 boost::variant 中逐个索引获取项目,就像使用 std::variant 一样
- 如何将排序的元素从数组中的起始索引获取到结束索引
- 按索引获取__m128成员?
- 通过(实际)监视器的索引获取其句柄
- 从 C++ 中的二维向量中的特定索引获取值
- RapidJSON 库通过索引获取数组中的值
- 通过其索引获取枚举值
- 奇怪的数组东西(数组索引获取值没有我设置它)
- 按索引获取 std::set 成员C++