C++ Tip: std::vector::reserve()

A small C++ tip that can save a lot of unnecessary work: std::vector::reserve() Whenever I’m loading data or building vectors from known sources (files, protobufs, APIs, etc.), I try to remember this. #cpp #cplusplus #programming #softwareengineering

  • text

`reserve()` can be a lot more than just optimization, too! If you try to store entities in a vector, and pass some pointers around for those entities, you'll soon find everything going haywire, because the first time the vector resizes, all of those pointers dangle. `reserve()` allows you to make use of the vector rather than moving to maps or smart pointers.

Not only that, but you avoid potential relocations while adding elements up to the reserved capacity. This also helps avoid memory fragmentation

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories