正在使std::映射分配器工作
Getting std::map allocator to work
我有一个非常基本的分配器:
template<typename T>
struct Allocator : public std::allocator<T> {
inline typename std::allocator<T>::pointer allocate(typename std::allocator<T>::size_type n, typename std::allocator<void>::const_pointer = 0) {
std::cout << "Allocating: " << n << " itens." << std::endl;
return reinterpret_cast<typename std::allocator<T>::pointer>(::operator new(n * sizeof (T)));
}
inline void deallocate(typename std::allocator<T>::pointer p, typename std::allocator<T>::size_type n) {
std::cout << "Dealloc: " << n << " itens." << std::endl;
::operator delete(p);
}
template<typename U>
struct rebind {
typedef Allocator<U> other;
};
};
当我将它与:"std::vector>"一起使用时,它工作得很好,然而,当我尝试将它与std::map之类的:一起使用时
int main(int, char**) {
std::map<int, int, Allocator< std::pair<const int, int> > > map;
for (int i(0); i < 100; ++i) {
std::cout << "Inserting the " << i << " item. " << std::endl;
map.insert(std::make_pair(i*i, 2*i));
}
return 0;
}
它无法编译(gcc 4.6),给出了一个非常长的错误,以:/usr/lib/gcc/x86_64-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/stl_tree.h:959:25: error: no match for call to ‘(Allocator<std::pair<const int, int> >) (std::pair<const int, int>::first_type&, const int&)’
因为分配器是第四个模板参数,而第三个参数是类似std::less
的比较器?所以CCD_ 3应该起作用。
此外,我认为您应该添加默认的ctor和复制ctor:
Allocator() {}
template<class Other>
Allocator( const Allocator<Other>& _Right ) {}
如果有人正在寻找通用方法:
template<class Key, class T,class Compare = std::less<Key>, class _Ax = Allocator<std::pair<const Key, T> >>
class Map : public std::map<Key, T, Compare, _Ax >
{
};
然后使用它,
Map<int,char> myMap;
myMap.insert<std::pair<int,char>(1,'o');
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- QSqlquery prepare()和bindvalue()不工作
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- C++ 已停止工作静态映射函数
- 使QTConcurrent ::映射与Lambdas一起工作
- C++STL映射键和值工作不正常
- std::以struct为键的映射未按预期工作
- 插入[n X n]矩阵类型的数据,并在运行时对其进行访问.将std::映射工作
- 不确定无序映射是如何工作的
- 无法使无序映射工作
- 从数组映射到整数在C++中无法正常工作
- 使多态性在C++映射中工作,而不会发生内存泄漏
- Boost::在gcc4.6不工作的情况下分配一个大映射的静态初始化
- 调用映射键来调用需要参数的函数-如何工作
- 文件映射是如何工作的
- 正在使std::映射分配器工作
- 无序映射它的工作原理
- openCV重映射与BORDER_REFLECT不工作