Using for_each on container with const_iterators?

Viewed 50

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.

2 Answers

You want for (auto& item : std::as_const(queue)) {}. It still calls begin() but it’s const so it picks the const overload.

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())) {}
Related