Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all elements but the first as a separate vector

Tags:

c++

c++11

vector

I'm trying to write a basic command-line program in C++. While the rest of the code probably has problems galore, too, the one I'm facing now is this: I've split the inputted line into pieces, but I can't figure out how to get all but the first so I can pass it down the line as the list of arguments for the command.

If this was Ruby, I'd do something like this, where parts is the array of space-separated arguments for the command:

command = parts[0]
args = parts[1..-1]

where parts is the array of bits that were space-separated.

TL;DR: How can I get all but the first elements of a vector?

If using another type makes it easier, feel free to say as much -- I don't think I'll have that much trouble porting it over.

I've tried using a deque, but I don't want to modify parts, just get pieces of it. I've also searched around on this site, but all of the questions that turn up are either related but solved in a way that I can't use, starts of a really hacky workaround that I'd rather avoid, or totally unrelated.


P.S. I'm not using namespace std, but std:: is a pain to type so I omitted it here. Please do provide it in your answers, where applicable.

P.P.S. I'm just (re)starting at C++ so please provide an explanation along with your answer.

like image 837
Nic Avatar asked Dec 03 '22 16:12

Nic


2 Answers

TL;DR: How can I get all but the first elements of a vector?

If you want a vector containing that then do this:

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

If you want only to access the vector elements then start from parts.begin()+1 until parts.end().

like image 198
Marius Bancila Avatar answered Dec 19 '22 17:12

Marius Bancila


The most idiomatic way would be to use iterators and make your function accept an iterator like this:

template<typename It>
void func(It begin, It end) { ... }

and then you pass your vector as:

func(begin(vector) + 1, end(vector));
like image 44
Shoe Avatar answered Dec 19 '22 19:12

Shoe