How could I go about getting the tail of a vector:
std::vector<int> Example {1,2,3,4,5};
//head = [1]
//tail = [2,3,4,5]
Python:
head = Array[0]
tail = Array[1:]
Haskell
myRecursiveFunction :: [Int] -> [Int]
myRecursiveFunction (x : xs) = x + 1 : myRecursiveFunction xs
I'm aware I could use an iterative STL algorithm, such as accumulate:
std::vector<int> Example {1,2,3,4,5};
std::accumulate(Example.begin() + 1, Example.end(), 0);
However this seems quite verbose, are there simpler solutions? I don't mind if the solution copies or views the tail, I'm just looking for a method to easily access the tail of a vector without using iterators.
Don't use accumulate
. That doesn't even do what you want. Just use the vector constructor:
std::vector<int>( example.begin() + 1, example.end() );
This builds a new vector in memory, and copies from element 1 to the end. If you want an actual identifier for it:
std::vector<int> example_slice( example.begin() + 1, example.end() );
If you're trying to pass these around for some kind of recursive process. You might want to reconsider. Maybe we're dealing with an XY problem here.
If by "getting the tail of the vector" you mean removal of first element or first n elements, use vector::erase
:
example.erase(example.begin()); // remove the first element
-- or --
example.erase(example.begin(), example.begin()+n); // remove the first n elements
If by "getting the tail of the vector" you mean saving its tail to another vector, use the range constructor:
vector<int> tail(example.begin()+n, example.end());
The closest to Python that I can think of is std::slice
:
std::valarray<int> Example {1,2,3,4,5};
auto head = Example[std::slice(0, 1, 1)];
auto tail = Example[std::slice(1, Example.size() - 1, 1)];
Not as simple as Python, but closer than your own example.
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