Reputation: 4297
I swear this is not a duplicate of any of the seemingly-endless number of threads on vector concatenation. For my case, in a derived class constructor I need to pass a std::vector<int>
to the base class constructor, but the passed vector needs to be a concatenation of two other vectors. Example:
#include <vector>
using namespace std;
struct Base {
Base(vector<int> numbers) {
//Do something with numbers
}
};
struct Derived: public Base {
Derived(vector<int> numbers):
Base(concatenate(numbers, {4,5,6})) {} //Is there a built-in "concatenate" function?
};
int main (int argc, char* argv[])
{
Derived D({1,2,3});
return 0;
}
I can obviously do this by writing my own concatenate
function, but I'm wondering if there is already a standard-library way to do this. None of the examples of vector concatenation I've found are suitable to use in an initialization list because they span multiple lines; I need a one-liner concatenation.
Upvotes: 3
Views: 1468
Reputation: 96241
OK since numbers
is passed by value we can use trickery by combining the initializer list insert
with the comma operator:
struct Derived: public Base {
Derived(vector<int> numbers):
Base((numbers.insert(numbers.end(), {4,5,6}), numbers)) {}
};
Upvotes: 6
Reputation: 31
To add a vector [b] to a vector [a]:
a.insert(a.end(), b.begin(), b.end());
If you don't want to alter a you can just copy it to a third vector.
Upvotes: 3