让std :: map allocator工作

时间:2011-06-09 16:33:39

标签: 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_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&gt;”但是,当我尝试将它与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&)’

结尾的极长错误

2 个答案:

答案 0 :(得分:16)

因为allocator是第4个模板参数,而第3个参数是std::less之类的比较器? 所以std::map<int, int, std::less<int>, Allocator< std::pair<const int, int> > >应该有用。

另外我认为你应该添加默认的ctor和copy ctor:

  Allocator() {}

  template<class Other>
  Allocator( const Allocator<Other>& _Right ) {}

答案 1 :(得分:0)

如果有人在寻找广义的方式:

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');