Search code examples
c++range-v3

How to iterate over c++ vector and operate on two values at a time using the range-v3 library?


Let's say I have a vector of numbers:

std::vector< int > v{ 1, 2, 3, 4 };

I want to iterate over the vector and operate on two at a time; that is, I want to operate on:

  • (1,2),
  • (2,3), and
  • (3,4).

I know there is a way to do this using Eric Neibler's range-v3 library (slated to be in C++20), but I can't remember the exact sequence of commands.


I could do this using iterators

for( auto begin = v.begin(); begin != (v.end()-1); begin++ ){
  // Do something with *begin and *(begin+1)
}

Using the range-v3 library would make this so much more elegant and readable. I just can't remember what the command is.


Solution

  • In Eric Niebler's library, this is known as a sliding view (live example):

    using namespace ranges;
    std::vector< int > v{ 1, 2, 3, 4 };
    
    for (const auto& p : v | views::sliding(2)) {
        std::cout << p[0] << ' ' << p[1] << '\n';
    }
    

    I don't think this particular view is included in C++20 out of the box, but I believe there's a fair chance of it appearing in the future. Unfortunately, zip_view had to be cut from P1035, so the "canonical" implementation via zip (zipping the range with itself minus the first element) will probably be a bit more involved as well.