加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:22:27 所属栏目:百科 来源:网络整理
导读:我发现自己写下了很多: int location =2;vectorint vec;vectorint::iterator it=vec.begin();/..../std::advance(it,location); 代替 it= it + 5; 什么是首选/推荐方式? 解决方法 添加只适用于随机访问迭代器. std :: 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读