Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::next for vector O(n) or O(1)?

Tags:

c++

In C++11 I use std::next because If I want to change vector to list, I dont have to change the rest of code.

For list, std::next is O(n), because I need to iterate all elements. But how is it for a vector? I have found this note on cppreference:

However, if InputIt or ForwardIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.

Does vector meet these requirements? And why "Legacy"?

like image 560
Martin Perry Avatar asked Apr 09 '19 07:04

Martin Perry


People also ask

How do you find the next element of a vector?

You can use std::next. Show activity on this post. In case you use the vector as a circular list (that is, you consider the first element as the "next" of the last element), you can use the modulo operator against the length of the vector.

What does next () do in C++?

std::next in C++ std::next returns an iterator pointing to the element after being advanced by certain no. of positions. It is defined inside the header file . It does not modify its arguments and returns a copy of the argument advanced by the specified amount.

What is an std::vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

What does std :: next return?

std::next. Return the n th successor of iterator it .


1 Answers

There is a plan of adding concepts (compile time type constraints) in C++20. The new standard is supposed to contain concepts like InputIterator or RandomAccessIterator. To distinguish between the concepts and the old trait-like requirements cppreference uses LegacyRandomAccessIterator and so on for pre-concept requirements and RandomAccessIterator and so for concept requirements.

And so yes, std::vector::iterator meets requirements of LegacyRandomAccessIterator and actually will be fulfilling RandomAccessIterator concept as well. This leads straight to conclusion that std::next called on vector::iterator has complexity O(1).

like image 117
bartop Avatar answered Sep 28 '22 01:09

bartop