Concatenating two std::vectors

后端 未结 25 2611
予麋鹿
予麋鹿 2020-11-22 12:00

How do I concatenate two std::vectors?

25条回答
  •  温柔的废话
    2020-11-22 12:35

    You can prepare your own template for + operator:

    template  
    inline T operator+(const T & a, const T & b)
    {
        T res = a;
        res.insert(res.end(), b.begin(), b.end());
        return res;
    }
    

    Next thing - just use +:

    vector a{1, 2, 3, 4};
    vector b{5, 6, 7, 8};
    for (auto x: a + b)
        cout << x << " ";
    cout << endl;
    

    This example gives output:

    1 2 3 4 5 6 7 8

提交回复
热议问题