Is it possible to use custom allocator for std::vector
internal allocations? If yes, how?
An std::vector manages its own memory. You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.
std::allocator is the default memory allocator for the standard library containers, and you can substitute your own allocators. This allows you to control how the standard containers allocate memory.
std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.
Although std::vector can be used as a dynamic array, it can also be used as a stack.
You basically have to implement your allocator type to conform to the Allocator concept.
The linked page lists all requirements of that type, but the core functionality is implemented in the allocate
member function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With