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}
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.
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 .
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With