提前为std :: vector std :: advance VS运算符添加迭代器+? [英] Advance iterator for the std::vector std::advance VS operator +?
问题描述
我发现自己经常写以下内容:
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
anddistance
. 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屋!