首页 > 解决方案 > 我可以将迭代器增加一个整数吗?

问题描述

std::map<int, int> m;
// initialize m...
//
int n=3;
for (std::map<int, int>::iterator iter = m.begin()+n; iter != m.end(); ++iter)
// Is the above line correct?
{}

如代码所示,我可以将迭代器增加一个整数吗?

标签: c++dictionaryiteratorstdstdmap

解决方案


只有当它是随机访问迭代器时,您才能对迭代器执行“指针运算”。std::setstd::multisetstd::map和的迭代std::multimap器不是随机访问迭代器。为地图迭代器有效地支持“increment by n”操作将需要在红黑树结构中进行一些额外的簿记,这将增加所有用户的开销。这是一个很少需要的操作,因此标准库不支持它。

您可以使用std::next(m.begin(), n). 这只是增加迭代器n时间的副本并返回结果。


推荐阅读