Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting tail of a vector?

Tags:

c++

vector

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.

like image 235
Babra Cunningham Avatar asked Dec 12 '16 05:12

Babra Cunningham


3 Answers

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.

like image 100
paddy Avatar answered Sep 27 '22 20:09

paddy


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());
like image 29
user31264 Avatar answered Sep 27 '22 21:09

user31264


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.

like image 23
Ken Y-N Avatar answered Sep 27 '22 20:09

Ken Y-N