简体   繁体   中英

How do I concatenate two vectors with one line of code

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.

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)) {}
}; 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM