Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit the growth of a vector in c++

Tags:

c++

vector

Is it possible to limit the vector.max_size() in order to limit the growth of a vector?

If not, is having a function to watch the vector.capacity() to ensure it doesn't go over a determined amount a viable substitute?

like image 607
Jason M. Avatar asked Nov 18 '25 12:11

Jason M.


2 Answers

Sort of. You can write a custom allocator and use it in a std::vector (the second template argument of the vector). The allocator needs to satisfy these requirements. However, doing this properly isn't simple. And your vector wouldn't just ignore push_back after the max size was met, it would throw.

like image 67
David Avatar answered Nov 20 '25 05:11

David


Not really. But you can define your own subclass of vector (or create completely new vector implementation of your own) which will permit to enforce this requirement if you really want to.

like image 23
mvp Avatar answered Nov 20 '25 03:11

mvp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!