Stl vector assign vs insert

I understand the semantics of the two operations, assigns them before the replacement with the given values. insert - inserts values ​​to the specified location (allocates new memory if necessary).

Also, is there any reason to teach one over the other? Or, to put it another way, is there any reason to use assignment instead of insertion.

+4
source share
3 answers

If you want to call the semantics of assign , assign a call - if you want to call the semantics of insert , insert the call. They are not interchangeable.

As for calling them to an empty vector, the only difference is that you do not need to specify an iterator to insert when you call assign . There may be a difference in performance, but this implementation is specific and almost certainly careless.

+4
source

assign and insert equivalent only if the vector is empty. If the vector is already empty, it is better to use assign , because insert falsely hints to the reader that there are surviving elements.

+6
source

assign() will delete everything that is already in vector , and then add new elements. insert() does not apply to any elements already in vector .

Also, if the vector parameter you are changing is empty, the difference is small.

+3
source

Source: https://habr.com/ru/post/1299131/


All Articles