Concatenating two std::vectors

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

How do I concatenate two std::vectors?

25条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 12:17

    Add this one to your header file:

    template  vector concat(vector &a, vector &b) {
        vector ret = vector();
        copy(a.begin(), a.end(), back_inserter(ret));
        copy(b.begin(), b.end(), back_inserter(ret));
        return ret;
    }
    

    and use it this way:

    vector a = vector();
    vector b = vector();
    
    a.push_back(1);
    a.push_back(2);
    b.push_back(62);
    
    vector r = concat(a, b);
    

    r will contain [1,2,62]

提交回复
热议问题