What is the most efficient way to append one std::vector to the end of another?

前端 未结 5 1162
旧巷少年郎
旧巷少年郎 2020-12-13 05:44

Let v1 be the target vector, v2 needs to be appended to the back of it.

I\'m now doing:

v1.reserve(v1.size() + v2.size()); 
copy(v2.begin(), v2.end()         


        
5条回答
  •  借酒劲吻你
    2020-12-13 06:37

    Probably better and simpler to use a dedicated method: vector.insert

    v1.insert(v1.end(), v2.begin(), v2.end());
    

    As Michael mentions, unless the iterators are input iterators, the vector will figure out the required size and copy appended data at one go with linear complexity.

提交回复
热议问题