如何为包含最多N个元素的std::multiset调用最大数量分配
How to callculate max number allocations for std::multiset containing maximum N elements?
我向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中引入(,而不是自己制作或简单地实现一个支持所需数量元素的简单多集。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- C++:将 std::set_union() 输出存储在 std::multiset 中
- 如何为包含最多N个元素的std::multiset调用最大数量分配
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 试图理解libstdc++对std::multiset的实现
- std::multiset::iterator = NULL 不再有效
- std::multiset<A>的模板参数 A、B 分别是什么意思,它是如何工作的?
- 在STD :: MultiSet中维护插入顺序
- 哪个元素将从 std::multimap::find 返回,同样,std::multiset::find
- std::multiset并查找中间元素
- std::multiset vs. std::<int>map<int, std::size_t> 用于保留多个可重复的整数值
- 在std::multiset中,如果找到一个元素,有一个函数或算法可以只擦除一个样本(单播或重复)
- 从std::multiset的第i个元素删除到末尾
- 用C++11将compare函数传递给std::multiset
- 输出“std::multiset”的唯一元素及其频率,使用C++中的std::算法(无循环)
- 对std::multiset内的相等范围进行排序
- 在“std::multiset”的唯一元素上迭代
- 如何使用std::multiset与多个比较器函数
- C++ std::set and std::multiset