2011-06-09 26 views
7

我有一個非常基本的分配:獲得的std ::地圖分配器工作

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 ::地圖這樣的:

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&)’

+0

爲什麼你認爲你需要一個自定義分配器? – 2011-06-09 16:47:21

回答

16

因爲分配器是第4個模板參數,而第三個參數是比較喜歡std::less? 所以std::map<int, int, std::less<int>, Allocator< std::pair<const int, int> > >應該工作。

此外,我想你應該添加默認構造函數和拷貝構造函數:

Allocator() {} 

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

+1爲正確的事情。只是一個nit - 不需要默認的構造函數 – 2011-06-09 17:34:42

+3

這是一個通用的轉換構造函數,而不是一個拷貝構造函數。但缺省構造函數是需要的... – Potatoswatter 2011-06-09 17:57:34

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