ranges/enumerateconst.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <print>
#include <vector>
#include <ranges>

// define different output for const and non-const objects:
void print(const auto& arg)
{
  std::println("const: {}", arg);
}
void print(auto&& arg)
{
  std::println("non-const: {}", arg);
}

int main()
{
  std::vector<int> coll{47, 11};

  for (const auto& val : coll) {
    print(val);    // coll elements are const
  }
  std::println("");

  for (const auto& val : coll | std::views::drop(1)) {
    print(val);    // coll elements are const
  }
  std::println("");

  for (const auto& [idx,val] : coll | std::views::enumerate) {
    print(val);    // coll elements are no longer const
  }
  std::println("");

  for (const auto& [idx,val] : coll | std::views::enumerate
                                    | std::views::as_const) {
    print(val);    // coll elements are const
  }
}