How do I reserve capacity ahead of time with std::set for embedded targets?

When working with `std::set` in C++, you cannot directly reserve capacity like you would with other containers such as `std::vector` or `std::deque` because `std::set` is usually implemented as a balanced tree structure (like a red-black tree) which manages its own memory dynamically. However, when targeting embedded systems, efficient memory management is crucial.

One approach to optimize memory usage in embedded targets is to pre-allocate a specific number of nodes for your `std::set` by using a custom allocator. This allows you to mitigate dynamic memory allocation during runtime, thus enhancing performance and predictability.


#include 
#include 
#include 

template
class CustomAllocator {
public:
    using value_type = T;

    CustomAllocator() = default;

    template
    CustomAllocator(const CustomAllocator&) {}

    T* allocate(std::size_t n) {
        if (n > std::numeric_limits<:size_t>::max() / sizeof(T)) {
            throw std::bad_alloc();
        }
        return static_cast(::operator new(n * sizeof(T)));
    }

    void deallocate(T* p, std::size_t) noexcept {
        ::operator delete(p);
    }
};

int main() {
    // Using custom allocator with std::set
    std::set, CustomAllocator> mySet;

    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);

    for (const auto& item : mySet) {
        std::cout << item << std::endl;
    }

    return 0;
}
    

C++ std::set embedded systems memory management custom allocator