c – 用于std :: vector std :: advance VS运算符的Advance迭代器

我发现自己写下了很多:
int location =2;
vector<int> vec;
vector<int>::iterator it=vec.begin();

/..../
std::advance(it,location);

代替

it= it + 5;

什么是首选/推荐方式?

解决方法

添加只适用于随机访问迭代器. std :: advance将与各种迭代器配合使用.只要你只处理迭代器到向量,它没有什么真正的区别,但是std :: advance会使你的代码更加通用(例如,你可以用一个列表来代替这个向量,而这个部分仍然可以使用).

编辑:对于那些关心的人来说,标准描述了进步和距离如下(§24.3.4/ 1):

Since only random access iterators provide + and – operators,the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are,therefore,constant time for them); for input,forward and bidirectional iterators they use ++ to provide linear time implementations.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...