c++ - 我可以将迭代器增加一个整数吗?
问题描述
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?
{}
如代码所示,我可以将迭代器增加一个整数吗?
解决方案
只有当它是随机访问迭代器时,您才能对迭代器执行“指针运算”。std::set
、std::multiset
、std::map
和的迭代std::multimap
器不是随机访问迭代器。为地图迭代器有效地支持“increment by n
”操作将需要在红黑树结构中进行一些额外的簿记,这将增加所有用户的开销。这是一个很少需要的操作,因此标准库不支持它。
您可以使用std::next(m.begin(), n)
. 这只是增加迭代器n
时间的副本并返回结果。
推荐阅读
- python - 如何正确压缩整个 python 标准库?
- flutter - 颤振导航器弹出对话框 - 错误 - 未处理的异常:NoSuchMethodError:方法'findAncestorStateOfType'被调用为null
- direct2d - 使用纹理数组作为 Direct2D 表面渲染目标
- python - Python Selenium 浏览器窗口无法打开
- java - ClassNotFoundException JavaRecursiveElementVisitor
- r - 如何计算字符串出现的次数
- javascript - discord.js var 令牌意外
- python - 使用 Soup 和 Python 抓取搜索结果,Split 只返回一个值而不是列表?
- javascript - javascript/jquery clearInterval 有效但有延迟
- java - 如何从 excel 中获取整数值并存储在 Soap UI 属性步骤中