Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} 
like image 642
Wizard Avatar asked May 27 '18 06:05

Wizard


People also ask

Is slicing possible in C++?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible. Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.

Is Valarray faster than vector?

Although the exact performance improvement undoubtedly varies, a quick test with simple code shows around a 2:1 improvement in speed, compared to identical code compiled with the "standard" implementation of valarray .


1 Answers

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

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

As @AlessandroFlati suggested I should clarify that this will include v1.end()

like image 165
DimChtz Avatar answered Sep 26 '22 01:09

DimChtz