开发者

Why only random-access-iterator implements operator+ in C++?

开发者 https://www.devze.com 2022-12-30 09:02 出处:网络
I\'d like get far next value for STL list iterator but it doesn\'t implement operator+, vector has it though. Why and how can I get the value where I want?

I'd like get far next value for STL list iterator but it doesn't implement operator+, vector has it though. Why and how can I get the value where I want?

I think I can do that if I call operator++ several times, but isn't that a little bit di开发者_运维百科rty?

What I want to do is the following:

list<int> l;
...omitted...
list<int>::iterator itr = l.begin() + 3; // but, list iterator does not have
                                         // operator+

What is the best solution for what I want?


You want to use std::advance:

list<int>::iterator itr = l.begin();
std::advance(itr, 3);

advance will use operator+ and complete in constant time if the iterator is random access while it will loop on operator++ and complete in linear time if the iterator is not random access.  

The reason for this is to give you control over complexity requirements. If you care about the complexity of your operation you use operator+ and get constant time but this only compiles with random access iterators. If you don't care about the complexity you use std::advance which will always work but the complexity will vary based on the iterator.


You can also use std::next (and prev) or the equivalents provided by Boost if you don't have access to C++11.

list<int>::iterator itr = std::next(l.begin(), 3);

Rationale: std::advance is awkward to use (it works by side-effect, not by returning a copy).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号