STL vector reserve() and copy()

前端 未结 5 767
情话喂你
情话喂你 2020-12-14 02:51

Greetings,

I am trying to perform a copy from one vector (vec1) to another vector (vec2) using the following 2 abbreviated lines of code (full test app follows):

5条回答
  •  囚心锁ツ
    2020-12-14 03:01

    Change reserve to resize():

    vec2.resize(vec1.size(), '\0');
    copy(vec1.begin(), vec1.end(), vec2.begin());
    

    I believe that is the fix you need.

    I can't give you a very good description on the difference, but basically reserve() makes sure you have enough space, and resize() actually inserts something in there.

提交回复
热议问题