How to implement Python-like slicing in C++20 Ranges TS?

The ranges TS has been merged into C++20. I was wondering what is the best way to implement Python-like slicing operations with that proposal? To be specific, assume a is a vector<int>, how to implement:

  • a[:5](first 5 elements)
  • a[5:](from the 5-th elements to the end)
  • a[2:4](the 2nd and the 3rd elements)
  • a[2::-1] (a[2], a[1], a[0])
  • a[4:1:-2] (a[4], a[2])

1 answer

  • answered 2018-12-05 21:38 J. Willus

    Here are all the snippets I was able to come up to match your examples, please take these as hints as how to use the current implementation of the TS.

    std::vector<int> elements{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    
    // First five elements
    std::vector<int> a = elements | ranges::view::take(5);
    
    // From the 5-th elements to the end
    std::vector<int> b = elements | ranges::view::drop(5);
    
    // The 2nd and 3rd elements
    std::vector<int> c = elements | ranges::view::slice(2, 4);
    
    // The first 3 elements, in reverse
    std::vector<int> d = elements | ranges::view::take(3) | ranges::view::reverse;
    
    // Elements 2-4 inclusive, reversed, and then taking every 2nd element
    std::vector<int> e = elements | ranges::view::slice(2, 5) | ranges::view::reverse | ranges::view::stride(2);