#include <iostream>
#include <functional>
#include <memory>
#include <map>
#include <unordered_map>
#include <vector>
using namespace std;
static constexpr long total_size = 1000000;
template<typename T>
class CountingAllocator
{
public:
shared_ptr<size_t> d_max = make_shared<size_t>(0u);
using value_type = T;
using pointer = T*;
CountingAllocator() = default;
template <typename S>
CountingAllocator(CountingAllocator<S> const& other): d_max(other.d_max) {}
size_t size() const { return *d_max; }
T* allocate(size_t size) {
size *= sizeof(T);
*d_max += size;
return reinterpret_cast<T*>(operator new(size));
}
void deallocate(void* ptr, size_t) {
operator delete(ptr);
}
friend bool operator== (CountingAllocator const& c0, CountingAllocator const& c1) {
return c0.d_max == c1.d_max;
}
friend bool operator!= (CountingAllocator const& c0, CountingAllocator const& c1) {
return !(c0 == c1);
}
};
template <typename T>
void size(char const* name) {
CountingAllocator<typename T::value_type> allocator;
T m(allocator);
for (int i = 0; i != total_size; ++i) {
m[i] = i;
}
cout << name << "=" << allocator.size() << "\n";
}
int main() {
size<map<long, long long, less<int>, CountingAllocator<pair<long const, long long>>>>("map");
size<unordered_map<long, long long, hash<long>, equal_to<long>, CountingAllocator<pair<long const, long long>>>>("unordered_map");
cout << "array=" << sizeof(long long[total_size]) << "\n";
return 0;
}
map= 48000000
unordered_map=40654880
array= 8000000
当然,数组的占用空间最小(每个元素没有开销)。我很惊讶使用unordered_map
与map
相比,平均每个元素的开销更小。除数据外再使用5个字似乎有点过多。
std::vector<int, custom_allocator>
。 - undefinedc
是最小的,因为它只存储了一半的数据。它存储了1000000个long long
实例,而a
和b
则存储了这些实例加上1000000个int
实例。 - undefined