Benefits of using reserve() in a vector - C++

后端 未结 7 1338
感动是毒
感动是毒 2020-12-15 04:13

What is the benefit of using reserve when dealing with vectors. When should I use them? Couldn\'t find a clear cut answer on this but I assume it is faster when you reserve

相关标签:
7条回答
  • 2020-12-15 05:07

    If you know the eventual size of the vector then reserve is worth using.

    Otherwise whenever the vector runs out of internal room it will re-size the buffer. This usually involves doubling (or 1.5 * current size) the size of the internal buffer (can be expensive if you do this a lot).

    The real expensive bit is invoking the copy constructor on each element to copy it from the old buffer to the new buffer, followed by calling the destructor on each element in the old buffer.

    If the copy constructor is expensive then it can be a problem.

    0 讨论(0)
提交回复
热议问题