【问题标题】:Getting std::map allocator to work让 std::map 分配器工作
【发布时间】:2011-09-11 21:04:18
【问题描述】:

我有一个非常基本的分配器:

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&lt;std::pair&lt;const int, int&gt; &gt;) (std::pair&lt;const int, int&gt;::first_type&amp;, const int&amp;)’

【问题讨论】:

  • 您认为为什么需要自定义分配器?

标签: c++ stl allocator


【解决方案1】:

因为分配器是第 4 个模板参数,而第 3 个参数是比较器,如std::less? 所以std::map&lt;int, int, std::less&lt;int&gt;, Allocator&lt; std::pair&lt;const int, int&gt; &gt; &gt; 应该可以工作。

另外我认为你应该添加默认 ctor 并复制 ctor:

  Allocator() {}

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

【讨论】:

  • +1 表示一切正常。只是一个 nit - 不需要默认构造函数
  • 这是一个通用的转换构造函数,而不是复制构造函数。但是需要默认的构造函数……
【解决方案2】:

如果有人正在寻找通用方式:

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

【讨论】:

    猜你喜欢
    • 2011-09-06
    • 2012-08-28
    • 2015-05-11
    • 2017-12-26
    • 2014-01-28
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多