我无法找到解决问题的方法。让我们假设我们有这样的地图的n个元素:
std::map<string, string> tmpMap;
我们也有这个地图的迭代器:
std::map<string, string>::iterator itTmpMap = tmpMap.begin();
我现在如何将迭代器更改为第四对? Compilator不允许我向迭代器添加一个整数。
Compilator error:
int a = 4;
itTmpMap = itTmpMap + a;
答案 0 :(得分:5)
使用函数std::advance()
。它需要一个参考,而不是返回一个新的迭代器,一个我从未理解的奇怪......
答案 1 :(得分:2)
使用std::advance(itTmpMap, 4);
map迭代器是双向迭代器,而不是随机访问迭代器。
答案 2 :(得分:1)
std::map
有一个双向迭代器。对于双向迭代器,未定义操作迭代器+整数类型。因此,为了获得itTmpMap + 4的等效迭代器,你有4次增加它。
C ++标准为这种操作定义了特殊功能。您可以使用返回类型为void的std::advance
。例如
std::advance( itTmpMap, 4 );
或者您可以使用std::next
返回对源增量迭代器的引用。例如
std::next( itTmpMap, 4 );
例如,从第四个迭代器开始遍历地图,你可以编写
std::for_each( std::next( tmpMap.begin(), 4 ), tmpMap.end(), SomeFunction );
答案 3 :(得分:0)
您需要将迭代器增加4次:
++itTmpMap;
++itTmpMap;
++itTmpMap;
++itTmpMap;
答案 4 :(得分:0)
std::map
的迭代器是双向的。有几个操作对这样的迭代器有效,但添加一个整数来移动它不是其中之一。有几种方法可以做到这一点:
// this will advance the iterator 4 times
for (unsigned int i = 0; i < 4; ++i)
itTmpMap++;
或者,首选方法
std::advance(itTmpMap, 4);