ranges/fromrange2.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 <list>
#include <set>
#include <ranges>

int main()
{
  std::vector data{47, 11, 42, 0, 8, 15};

  std::vector<int> v1{data.begin(), data.end()};
  std::println("v1: {}", v1);                           // OK

  std::vector v2{data.begin(), data.end()};
  std::println("v2: {}", v2);                           // ERROR: elements are iterators

  std::vector v3(data.begin(), data.end());             // OK (note: parentheses)
  std::println("v3: {}", v3);

  std::vector v4{std::from_range, data};                // OK
  std::println("v4: {}", v4);

  auto vPrimes = std::views::iota(1, 100)               // values from 1 to 99
                  | std::views::filter(isPrime)         // only prime numbers
                  | std::views::take(10);               // at most 10

  std::vector<int> v5{vPrimes.begin(), vPrimes.end()};  // ERROR: no common range

  std::vector<int> v6{std::from_range, vPrimes};        // OK
  std::println("v6: {}", v6);
}