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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With