Can I increment an iterator by just adding a number?(我可以通过添加一个数字来增加一个迭代器吗?)
问题描述
我可以使用迭代器进行正常计算,即通过添加一个数字来增加它吗?
Can I do normal computations with iterators, i.e. just increment it by adding a number?
例如,如果我想删除元素 vec[3]
,我可以这样做吗:
As an example, if I want to remove the element vec[3]
, can I just do this:
std::vector<int> vec;
for(int i = 0; i < 5; ++i){
vec.push_back(i);
}
vec.erase(vec.begin() + 3); // removes vec[3] element
它适用于我 (g++),但我不确定它是否保证有效.
It works for me (g++), but I'm not sure if it is guaranteed to work.
推荐答案
如果迭代器是随机访问迭代器就可以工作,vector的迭代器是哪个(见参考).可以使用 STL 函数 std::advance
推进通用迭代器,但由于它不返回迭代器,我倾向于使用 + 如果可用,因为它看起来更干净.
It works if the iterator is a random access iterator, which vector's iterators are (see reference). The STL function std::advance
can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner.
C++11 笔记
现在有 std::next
和 std::prev
,做返回迭代器,所以如果你在模板领域工作,你可以使用它们来推进通用迭代器并且仍然有干净的代码.
Now there is std::next
and std::prev
, which do return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.
这篇关于我可以通过添加一个数字来增加一个迭代器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以通过添加一个数字来增加一个迭代器吗?


- 将函数的返回值分配给引用 C++? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- GDB 不显示函数名 2022-01-01