如何为包含最多N个元素的std::multiset调用最大数量分配

How to callculate max number allocations for std::multiset containing maximum N elements?

本文关键字:multiset std 调用 最大数 分配 元素 包含最      更新时间:2023-10-16

我向std::multimap推送了6个对象,但在控制台中看到了分配器的8个输出。为什么?总是N+2吗?如何计算N个元素的最大分配数量?

我想在分配器中使用静态数组,并返回指向数据局部性的it元素的指针。

template <class T>
struct Mallocator {
typedef T value_type;
Mallocator() = default;
template <class U> constexpr Mallocator(const Mallocator<U>&) noexcept {}
T* allocate(std::size_t n) {
if (n > std::numeric_limits<std::size_t>::max() / sizeof(T)) throw std::bad_alloc();
if (auto p = static_cast<T*>(std::malloc(n * sizeof(T)))) { std::cout << "allocate" << std::endl; return p; }
throw std::bad_alloc();
}
void deallocate(T* p, std::size_t) noexcept { std::cout << "free" << std::endl;  std::free(p); }
};
template <class T, class U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; }
template <class T, class U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; }
int main()
{
std::multiset<int, std::less<int>, Mallocator<int>> hashMap;
hashMap.insert(1);
hashMap.insert(2);
hashMap.insert(3);
hashMap.insert(4);
hashMap.insert(5);
hashMap.insert(6);
_getch();
}

我认为没有指定multiset、set等的实现方式。对于不同的平台/STL/版本,您要查找的数字可能不同,或者随着分配总数的增加而意外增加。

我建议您使用多态分配器(在C++17中引入(,而不是自己制作或简单地实现一个支持所需数量元素的简单多集。