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.
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.
Explanation: Vector & deque container provides random access iterators.
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).
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.
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
According to container requirements described in Table 96 of the C++ Standard function end()
has
constant complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With