Search code examples
c++foreachcontainers

Using for_each on container with const_iterators?


If you iterate on an std container with this elegant formula:

for (auto& item: queue) {}

It will be using queue's begin and end functions.

Is there a way to use cbegin and cend without modifying the queue's source?

I tried with

for (const auto& item: queue) {}

But if begin or end is missing, it doesn't compile.


Solution

  • Is there a way to use cbegin and cend without modifying the queue's source?

    In C++20, you can use queue.cbegin() and queue.cend() to construct a ranges::subrange:

    #include <ranges>
    
    for (auto& item: std::ranges::subrange(queue.cbegin(), queue.cend())) {}