Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl vector assign vs insert

Tags:

c++

stl

vector

I understand the semantics of the 2 operations , assign- erases before replacing with supplied values. insert - inserts values at specified location(allocates new memory if necessary).

Apart from this is there any reason to preffer one over the other? Or to put it another way, is there any reason to use assign instead of insert.

like image 252
Pradyot Avatar asked Jan 22 '10 17:01

Pradyot


3 Answers

assign and insert are only equivalent if the vector is empty to begin with. If the vector is already empty, then it's better to use assign, because insert would falsely hint to the reader that there are existing elements to be preserved.

like image 129
Emile Cormier Avatar answered Oct 08 '22 02:10

Emile Cormier


If you wish to invoke the semantics of assign, call assign - if you wish to invoke the semantics of insert, call insert. They aren't interchangeable.

As for calling them on an empty vector, the only difference is that you don't need to supply an iterator to insert at when you call assign. There may be a performance difference, but that's implementation specific and almost certainly negligable.

like image 24
JoeG Avatar answered Oct 08 '22 02:10

JoeG


assign() will blow away anything that's already in the vector, then add the new elements. insert() doesn't touch any elements already in the vector.

Other than that, if the vector you are modifying starts out empty, there is little difference.

like image 33
John Dibling Avatar answered Oct 08 '22 04:10

John Dibling