提前为std :: vector std :: advance VS运算符添加迭代器+? [英] Advance iterator for the std::vector std::advance VS operator +?

查看:75
本文介绍了提前为std :: vector std :: advance VS运算符添加迭代器+?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己经常写以下内容:

I found myself writing the following a lot:

int location =2;
vector<int> vec;
vector<int>::iterator it=vec.begin();

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

代替

 it= it + 5;

首选/推荐方式是什么?

what is the Preferred/Recommended way ?

推荐答案

添加仅适用于随机访问迭代器. std :: advance 将与各种迭代器一起使用.只要您仅将迭代器处理为向量,就没有任何实际区别,但是 std :: advance 可使您的代码更通用(例如,您可以替换 list 表示 vector ,然后该部分仍然有效).

Adding will only work with random access iterators. std::advance will work with all sorts of iterators. As long as you're only dealing with iterators into vectors, it makes no real difference, but std::advance keeps your code more generic (e.g. you could substitute a list for the vector, and that part would still work).

对于关心的人,该标准对 advance distance 进行了如下描述(第24.3.4/1节):

For those who care, the standard describes advance and distance as follows (§24.3.4/1):

由于只有随机访问迭代器提供+和-运算符,所以该库提供了两个功能模板 advance distance .这些函数模板将 + -用于随机访问迭代器(因此,它们的时间恒定).对于输入,正向和双向迭代器,它们使用 ++ 提供线性时间实现.

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 ++ 11开始,标准为 std :: next 添加了一个参数,因此您可以使用它(和 std :: prev).与 std :: advance 的不同之处在于,它返回修改后的迭代器( std :: advance 不提供),在某些情况下会很方便.

Also note that starting with C++11, the standard added a parameter to std::next, so you can advance by a specified amount using it (and std::prev similarly). The difference from std::advance is that it returns the modified iterator (which std::advance doesn't), which can be convenient in some cases.

这篇关于提前为std :: vector std :: advance VS运算符添加迭代器+?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆