Search code examples
c++c++11vectoriterable

How to "cut" vector in c++ like python syntax


In python if I have some iterable can I do something like this:

v = v[n:k] // 
for i in v[3:]:
     "do something"

and now in C++ I want to this:

vector<int> v = {1,2,3,4,5,6,7,8}
v = v[3:5]; 

Or something like this:

for(auto n: v[2:end])
       "do something";

I tried to find the syntax for this problem but haven't found anything yet.


Solution

  • Prior to C++20, you can always do:

    for(auto i : std::vector(v.begin() + 2, v.begin() + 5))
    {
        foo(i);
    }
    

    However it is not recommended as it creates a new vector by copying all elements needed. It would be better to just do a iterator based for loop:

    for(auto it = v.begin() + 2; it != v.begin() + 5; ++it) 
    {
        foo(*it);
    }
    // or
    for(size_t index = 2; index != 5; ++index) 
    {
        foo(v[index]);
    }
    

    With C++20 introducing span, you can do:

    for(auto i : std::span(v.begin() + 2, v.begin() + 5))
    {
        foo(i);
    }
    

    It uses the same syntax as the first one, without the need of copying elements.


    Also I believe std::vector(&v[2], &v[5]) and std::span(&v[2], &v[5]) are also valid, but I need someone to confirm it.