简体   繁体   中英

Does vector.reserve() optimize for vector.insert()

I understand that vector.reserve() adds new spaces to the end for new additions to a vector, but will the vector re-copy if I insert a value in? If i reserve a size 1 bigger than the current size and insert a value in, will it recopy the entire vector or optimize it so it doesn't do that?

reserve(X) makes sure that the capacity() is at least X. It can be higher due to rounding or prior bigger reservations.

If the capacity is sufficient, methods that adds one or more elements to the vector will not cause a reallocation.

If the capacity grows, either because of a reserve or automatically when adding new elements, existing elements will need to be copied (or moved).

Reserve force a reallocation if the reserve value is greater than the capacity, if that happen the moving/copying happens when called and not on insert. Also all iterators will be invalidated.

Calling reserve with a value one higher than capacity is counter productive as the insert will do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM