ranges/to2.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 <ranges>
#include <chrono>

int main()
{
  std::vector<int> coll{47, 11, 0, 8, 15, -11, 7};
  std::println("coll: {}", coll);

  auto isOdd = [] (auto val) { return val % 2 != 0; };
  auto asSeconds = [] (auto val) { return std::chrono::milliseconds{val}; };

  // store all processed milliseconds objects in a container:
  auto lst = coll | std::views::filter(isOdd)
                  | std::views::transform(asSeconds)
                  | std::ranges::to<std::list>();
  // and process them further:
  std::println("lst:  {}", lst);

}