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

If the container probably contains a large number of elements, in terms of performance, you should write

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

or should access the end of the container outside the loop

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

I'm just wondering if there is std::end O (1) for containers like collections and lists, as well as vectors.

+7
c ++
source share
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

+5
source share

In accordance with the requirements of the container described in Table 96 of the Standard Function C ++ end() , constant complexity.

+4
source share

All Articles