Practical examples for the range-v3 library

This page contains examples for the range-v3 library to get you started. It is being continuosly updated. To try out the library, add #include <range/v3/all.hpp> in https://wandbox.org/.


Binary to decimal conversion

std::vector<int> v = {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

Caesar cipher

Note: Single words only.
std::string s("apple");    
unsigned short 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

Dot product

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);
};

Permutations with repetition

Note: This is the equivalent of nested for loops.

const std::vector<char> v = {'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
// ...

Permutations without repetition

Note: Sort the sequence first.

std::string s = "cab";
ranges::sort(s);
do {
    std::cout << s << '\n';
} while (ranges::next_permutation(s));
// abc
// acb
// bac
// bca
// cab
// cba

Shannon entropy

std::vector<double> v = {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

Triangular numbers

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

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);
// [1,3,6,10,15,21,28,36,45,55]

Calculate area with midpoint rule

Note: Midpoint Riemann integral.

auto steps = 5;
auto a = 0.0;
auto b = 2.0;
auto dx = (b-a)/steps; // 0.4
auto f = [](auto x){return x*x*x;};
    
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(f),
      0.0); // 0.4*(0.008 + 0.216 + 1 + 2.744 + 5.832) = 3.92

© Walletfox.com, 2018