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.
这篇关于我可以通过添加一个数字来增加一个迭代器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以通过添加一个数字来增加一个迭代器吗?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
