Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is std::end guaranteed to be O(1) for all container types? [duplicate]

Tags:

c++

If a container is likely to contain a large number of items, from a performance perspective, should one write

for (auto p = std::begin(container); p != std::end(container); ++p) {...}

or should one access the container's end outside the loop

const auto& theEnd = std::end(container);
for (auto p = std::begin(container); p != theEnd; ++p) {...}

I just wonder if std::end is O(1) for containers like sets and lists as well as vectors.

like image 931
user3918490 Avatar asked Aug 07 '14 13:08

user3918490


People also ask

Which STL collection guarantees the uniqueness of the stored content?

set::begin() and set::end() in C++ STL. Sets are a type of associative container in which each element has to be unique because the value of the element identifies it.

Which container provides random access to any of the elements of container?

Explanation: Vector & deque container provides random access iterators.

Which of the following STL containers keeps the elements in sorted order?

Associative containers implement sorted data structures that can be quickly searched (O(log n) complexity). Map: Collection of key-value pairs, sorted by keys, keys are unique (class template).

Which container has faster insertion?

The std::deque (double-ended queue) is a container that allows fast insertion of objects at both its beginning and its end. While the std::vector uses a single piece of memory, the std::deque splits memory into equal chunks.


2 Answers

Yes, the complexity for end() is constant for all containers. The table "Container requirements" in C++ Standard 23.2.1 says so:

a.end() constant

like image 106
Wojtek Surowka Avatar answered Sep 25 '22 20:09

Wojtek Surowka


According to container requirements described in Table 96 of the C++ Standard function end() has constant complexity.

like image 44
Vlad from Moscow Avatar answered Sep 24 '22 20:09

Vlad from Moscow