Home > database >  Using for_each on container with const_iterators?
Using for_each on container with const_iterators?

Time:02-05

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.

CodePudding user response:

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