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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?