Practical examples for the range-v3 library

This page contains examples for the range-v3 library, the predecesor of C++20 ranges. It is being continuosly updated. To try out the library, add #include <range/v3/all.hpp> into https://wandbox.org/.


auto const v = std::vector<unsigned> {1,1,1,0}; 
auto val = ranges::inner_product(  
                   v | ranges::view::reverse, // [0,1,1,1]
                   ranges::view::generate([n = 1] () mutable {return (n <<= 1) >> 1;}), // [1,2,4,8...]
                   0); // 0*1+1*2+1*4+1*8 = 14

Note: Single words only. Compiles with CLANG 8.0.0 and GCC 8.2.0. Doesn't compile with GCC 9.0.0.

auto s = std::string {"apple"};    
auto shift = 11;
auto encrypted = ranges::to_<std::string>( s | 
                          ranges::view::transform([](char c){ return tolower(c);}) |
                          ranges::view::transform([&shift](char c) -> char{
                                return 'a' + (c - 'a' + shift) % 26;})
                 ); // laawp

Note: This is the equivalent of ranges::inner_product.

auto dotProduct = [](const auto& v1, const auto& v2){
                                return ranges::accumulate(
                                              ranges::view::zip_with(
                                                      [](double a, double b){ return a*b; }, v1, v2), 
                                       0.0);};

Note: This is the equivalent of nested for loops.

auto const v = std::vector<char> {'a', 'b', 'c'}; 
auto rng = ranges::view::cartesian_product(v,v,v);
for(auto [x,y,z] : rng)
    std::cout << x << ' ' << y <<  ' ' << z << '\n';
// 27 permutations with repetition
// a a a
// a a b
// a a c
// a b a
// a b b
// ...

Note: Sort the sequence first.

auto s = std::string{"cab"};
ranges::sort(s);
do {
    std::cout << s << '\n';
} while (ranges::next_permutation(s));

// abc
// acb
// bac
// bca
// cab
// cba

auto v = std::vector<double> {0.5,0.25,0.125,0.125};
auto val = ranges::accumulate(
                   v | ranges::view::transform([](auto p){return -p*std::log2(p);}),
                   0.0); // 1.75

auto rng = ranges::view::generate([n = 0] () mutable { n++; return n*(n+1)/2;}) | 
           ranges::view::take(10);
// [1,3,6,10,15,21,28,36,45,55]

Note: Alternatively, we could use single-line generation created by @flex_ferrum.

auto rng = ranges::view::generate([n = 1, cur = 1]() mutable {return (cur = n++), (n)*(cur)/2;}) |
           ranges::view::take(10);

Note: Midpoint Riemann integral.

auto steps = 5;
auto a = 0.0;
auto b = 2.0;
auto dx = (b-a)/steps; // 0.4
    
auto area = 
   dx * ranges::accumulate(
      // generates [0.2, 0.6, 1, 1.4, 1.8]
      ranges::view::generate_n([a,dx,i = 0] () mutable {return a + dx*(0.5 + i++);}, steps) |
      // generates pow3 [0.008, 0.216, 1, 2.744, 5.832]
      ranges::view::transform([](auto x){return x*x*x;}),
      0.0); // 0.4*(0.008 + 0.216 + 1 + 2.744 + 5.832) = 3.92