tags:

views:

307

answers:

3

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.

+2  A: 

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.

Joe Gauterin
+3  A: 

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.

Emile Cormier
+1  A: 

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.

John Dibling