如何从向量映射中迭代向量

How to iterate a vector from a map of vectors?

本文关键字:向量 迭代 映射      更新时间:2023-10-16

我的地图是用向量构建的,我想迭代它,但我不知道怎么做!

WayMap::iterator it;
for ( it = MyWayMap.begin(); it != MyWayMap.end(); it++ ) 
// Loop the Whole Way Map
{
for(it->second.nodeRefList.begin();it->second.nodeRefList != it->second.nodeRefList.rbegin()-1;it->second.nodeRefList++);
// Loop The Whole Nodes of Each way
}
}

注释已经为您提供了所需的所有提示。

如果我们假设it->second.nodeRefList是一个容器(而不是迭代器(,并且行号对应于内部循环,那么内部循环看起来应该或多或少像

for(auto j = it->second.nodeRefList.begin(); j != it->second.nodeRefList.end(); ++j)
; // do something with node iterator (j)

更好的是,使用基于范围的循环

for (auto &node : it->second.nodeRefList)
; // do something with node

要使用连续元素计算距离,可以使用两个以步调一致的移动的迭代器

auto &nodes = it->second.nodeRefList;
for (auto i1 = nodes.begin(), i2 = i1 + 1; i2 != nodes.end(); ++i1, ++i2) {
auto dist = euclidean_distance(*i1, *i2);
// ...
}