我在代码中使用 unordered_multiset 有以下两个原因,
- 应该很容易找到或查找数据。
- 应该支持加载重复值。
unordered_multiset 通常比 multisets & vector 快得多,无论是插入还是查找,有时甚至是删除。
但不好的是,它占用了太多的内存。
我在 unordered_multiset 中存储了无符号的 __int64(8 字节)值,并正确清除了 unordered_multiset 中的值。谁能解释一下,为什么要占用内存以及如何解决这种内存消耗?
我在代码中使用 unordered_multiset 有以下两个原因,
unordered_multiset 通常比 multisets & vector 快得多,无论是插入还是查找,有时甚至是删除。
但不好的是,它占用了太多的内存。
我在 unordered_multiset 中存储了无符号的 __int64(8 字节)值,并正确清除了 unordered_multiset 中的值。谁能解释一下,为什么要占用内存以及如何解决这种内存消耗?
std::您可以通过为容器提供自定义分配器来更好地衡量容器使用了多少空间,该分配器记录要求分配多少空间。
例如
std::size_t total_allocation = 0;
template< class T >
struct logging_allocator
{
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using propagate_on_container_move_assignment = std::true_type;
template< class U > struct rebind { using other = logging_allocator<U>; };
using is_always_equal = std::true_type;
pointer address( reference x ) const { return base.address(x); }
const_pointer address( const_reference x ) const{ return base.address(x); }
pointer allocate( size_type n, const_pointer hint = nullptr ){
total_allocation += n;
return base.allocate(n, hint);
}
pointer allocate( size_type n, const void * hint){
total_allocation += n;
return base.allocate(n, hint);
}
pointer allocate( size_type n ){
total_allocation += n;
return base.allocate(n, hint);
}
void deallocate( T* p, size_type n ) {
total_allocation -= n;
return base.deallocate(p, n);
}
size_type max_size() const {
return base.max_size();
}
void construct( pointer p, const_reference val ) {
total_allocation += sizeof(T);
return base.construct(p, val);
}
template< class U, class... Args >
void construct( U* p, Args&&... args ) {
total_allocation += sizeof(U);
return base.construct(p, args...);
}
void destroy( pointer p ) {
total_allocation -= sizeof(T);
return base.destroy(p);
}
template< class U >
void destroy( U* p ) {
total_allocation -= sizeof(U);
return base.destroy(p);
}
private:
std::allocator<T> base;
}