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

前端 未结 5 1164
旧巷少年郎
旧巷少年郎 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:25

    If you have a vector of pod-types, and you really need the performance, you could use memcpy, which ought to be faster than vector<>.insert(...):

    v2.resize(v1.size() + v2.size());
    memcpy((void*)&v1.front(), (void*)&v2[v1.size()], sizeof(v1.front())*v1.size());
    

    Update: Although I would only use this if performance is really, really, needed, the code is safe for pod types.

提交回复
热议问题