Hash Sets using std::unordered_set

Using a Custom Allocator with std::unordered_set

How can I use a custom allocator with std::unordered_set?

Abstract art representing computer programming

std::unordered_set allows you to specify a custom allocator type as the fourth template parameter. This can be useful for specialized memory management or for integration with custom memory allocation libraries.

Here's an example of using a custom allocator with std::unordered_set:

#include <iostream>
#include <unordered_set>

template <typename T>
struct CustomAllocator {
  using value_type = T;

  CustomAllocator() = default;

  template <typename U>
  CustomAllocator(const CustomAllocator<U>&) {}

  T* allocate(std::size_t n) {
    std::cout << "Allocating " << n
      << " elements\n";
    return static_cast<T*>(
      ::operator new(n * sizeof(T)));
  }

  void deallocate(T* p, std::size_t n) {
    std::cout << "Deallocating " << n 
      << " elements\n";
    ::operator delete(p); 
  }
};

int main() {
  std::unordered_set<
    int, std::hash<int>,
    std::equal_to<int>,
    CustomAllocator<int>>
      Set{1, 2, 3};
}
Allocating 16 elements
Allocating 1 elements
Allocating 1 elements
Allocating 1 elements
Deallocating 16 elements
Deallocating 1 elements
Deallocating 1 elements
Deallocating 1 elements

In this example:

  • We define a¬†CustomAllocator¬†struct that implements the necessary functions for an allocator:¬†allocate()¬†and¬†deallocate()
  • Inside¬†allocate(), we print a message and then allocate memory using the global¬†::operator new
  • Inside¬†deallocate(), we print a message and then free the memory using¬†::operator delete
  • We specify¬†CustomAllocator<int>¬†as the fourth template argument when creating the¬†std::unordered_set

When we insert or erase elements from the set, our custom allocator's allocate() and deallocate() functions are called, as evident from the output.

Using a custom allocator allows you to have fine-grained control over how memory is allocated and freed for the elements stored in the std::unordered_set.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved