C++ 让std::map分配器工作
我有一个非常基本的分配器:C++ 让std::map分配器工作,c++,stl,allocator,C++,Stl,Allocator,我有一个非常基本的分配器: 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_point
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::分配器{
内联类型名称std::分配器::指针分配(类型名称std::分配器::大小\类型n,类型名称std::分配器::常量\指针=0){
std::cout,因为分配器是第四个模板参数,而第三个参数是类似于std::less
的比较器?
所以std::map>
应该是可行的
另外,我认为您应该添加默认ctor和复制ctor:
Allocator() {}
template<class Other>
Allocator( const Allocator<Other>& _Right ) {}
Allocator(){}
模板
分配器(常量分配器&_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 >
{
};
模板
类映射:公共std::Map
{
};
然后用它,
Map<int,char> myMap;
myMap.insert<std::pair<int,char>(1,'o');
Map-myMap;
myMap.insertWhy你认为你需要一个自定义分配器?+1来确保一切正常。只需要一个nit-不需要默认构造函数这是一个通用转换构造函数,不是副本构造函数。但是需要默认构造函数…
Map<int,char> myMap;
myMap.insert<std::pair<int,char>(1,'o');