Search code examples
c++vectorslice

Slicing a vector in C++


Is there an equivalent of list slicing [1:] from Python in C++ with vectors? I simply want to get all but the first element from a vector.

Python's list slicing operator:

list1 = [1, 2, 3]
list2 = list1[1:]  

print(list2) # [2, 3]

C++ Desired result:

std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2;
v2 = v1[1:];

std::cout << v2 << std::endl;  //{2, 3}

Solution

  • This can easily be done using std::vector's copy constructor:

    v2 = std::vector<int>(v1.begin() + 1, v1.end());
    

    However please note that this will make a copy of the existing elements. For a large array this may be slow, and there is additional overhead due to the additional allocation required.

    If you do not need a copy, and simply want to read but not modify the elements, use a std::span instead.