I would like to know if calling std::advance on an iterator of std::multiset is done in constant time.
Asked
Active
Viewed 1,395 times
0
-
2This question shows no sign of effort made to find the solution yourself. Just looking up cppreference would have sufficed. – Walter Nov 06 '18 at 14:42
-
1Oh dear @Walter, I only wish I could show you my browsing history. cppreference doesn't say what kind of iterator can be obtained from std::multiset, Hence, I wasn't sure if std::advance can be done in constant time. It would be great if didn't make assumptions on the nature of questions asked here. You know, most of us (like me) who use the internet aren't so well versed with C++ and are making an effort to learn. Getting a -1 will only discourage us further. – Gautham Nov 06 '18 at 19:32
2 Answers
5
No, only random access iterators can advance in constant time. Otherwise, it's linear time on the distance.

Jeffrey
- 11,063
- 1
- 21
- 42

Matthieu Brucher
- 21,634
- 7
- 38
- 62
-
-
-
Well, at worst linear. In theory one could write a multiset with log-speed advance iterators. It would, however, cost some performance (not standards-breaking, just a constant factor) in other operations, and I am unaware of any std implementation that does this. – Yakk - Adam Nevraumont Nov 06 '18 at 15:13
-
But how do I know if std::multiset returns a random access iterator? cppreference page only says that the "begin" method for multiset returns only iterator (doesn't mention which kind) - https://en.cppreference.com/w/cpp/container/multiset/begin – Gautham Nov 07 '18 at 13:59
-
1As you can see in the members of multiset in https://en.cppreference.com/w/cpp/container/multiset, the iterators are bidirectional, not random. – Matthieu Brucher Nov 07 '18 at 14:13
4
From std::advance
, we see that
Complexity
Linear. However, if InputIt additionally meets the requirements of RandomAccessIterator, complexity is constant.
As any template from the std::*map
and std::*set
family doesn't fulfill the RandomAccessIterator
requirements, it's linear. From e.g. here:
Member types
[...]
iterator
Constant BidirectionalIterator
const_iterator
Constant BidirectionalIterator