fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <memory>
  4. #include <map>
  5. #include <unordered_map>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. static constexpr long total_size = 1000000;
  11.  
  12. template<typename T>
  13. class CountingAllocator
  14. {
  15. public:
  16. shared_ptr<size_t> d_max = make_shared<size_t>(0u);
  17. using value_type = T;
  18. using pointer = T*;
  19.  
  20. CountingAllocator() = default;
  21. template <typename S>
  22. CountingAllocator(CountingAllocator<S> const& other): d_max(other.d_max) {}
  23. size_t size() const { return *d_max; }
  24. T* allocate(size_t size) {
  25. size *= sizeof(T);
  26. *d_max += size;
  27. return reinterpret_cast<T*>(operator new(size));
  28. }
  29. void deallocate(void* ptr, size_t) {
  30. operator delete(ptr);
  31. }
  32. friend bool operator== (CountingAllocator const& c0, CountingAllocator const& c1) {
  33. return c0.d_max == c1.d_max;
  34. }
  35.  
  36. friend bool operator!= (CountingAllocator const& c0, CountingAllocator const& c1) {
  37. return !(c0 == c1);
  38. }
  39. };
  40.  
  41. template <typename T>
  42. void size(char const* name) {
  43. CountingAllocator<typename T::value_type> allocator;
  44. T m(allocator);
  45. for (int i = 0; i != total_size; ++i) {
  46. m[i] = i;
  47. }
  48. cout << name << "=" << allocator.size() << "\n";
  49. }
  50.  
  51. int main() {
  52. size<map<long, long long, less<int>, CountingAllocator<pair<long const, long long>>>>("map");
  53. size<unordered_map<long, long long, hash<long>, equal_to<long>, CountingAllocator<pair<long const, long long>>>>("unordered_map");
  54. cout << "array=" << sizeof(long long[total_size]) << "\n";
  55. return 0;
  56. }
Success #stdin #stdout 0.5s 66028KB
stdin
Standard input is empty
stdout
map=48000000
unordered_map=40654880
array=8000000