ranges/elemconst.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>

int main()
{
  std::vector data{47, 11, 5};
  std::println("data: {}", data);

  // iterating over the vector elements using a take view:
  for (const auto& val : data | std::views::take(5)) {
    // val is: const int&
    std::println("- process: {}", val);                 // OK: read access
    //val *= 10; // ERROR: no write access
  }
  std::println("data: {}", data);

  // iterating over the vector elements using a view to enumerate them:
  for (const auto& elem : data | std::views::enumerate) {
    // elem is: const std::tuple&
    std::println("- process: {}", std::get<1>(elem));   // OK: read access
    std::get<1>(elem) *= 10;                            // \BOOPS: write access works
  }
  std::println("data: {}", data);

  // iterating over the vector elements using a view to enumerate them:
  for (const auto& [idx,val] : data | std::views::enumerate) {
    // val is: int&
    static_assert(std::same_as<decltype(val),int&>);
    std::println("- process: {}", val);   // OK: read access
    val *= 10;                            // \BOOPS: write access works
  }
  std::println("data: {}", data);
}