search

Home  >  Q&A  >  body text

C++ 模板 map 如何根据 key 排序

定义了一个

template <typename T>
std::map<const T, std::list<const T>*> map;

实际使用时 T 可能会是 char*,也可能是 long
需要针对 T 的类型进行排序,可是单纯使用

struct CompareByLongValue {
    bool operator()(const long& k1, const long& k2) {
        return k1 < k2;
    }
};

或是添加 template 声明后强制转换都编译过不去,求解


忧郁的更新:

实际上,我想将上面的那个 map 放到一个模板类里面去,在类内部实际上只
支持为数不多的类型操作,比如 long, char*,所以想在类内部自动排序。

template <typename T>
class Mapping {
   public:
    Mapping();
    virtual ~Mapping();

   private:
    std::map<const T, std::list<const T>*>* mapping_;
};

如果在 map 定义的时候传入一个如下定义的结构体:

template <typename T>
struct CompareByLongValue {
    bool operator()(const T& k1, const T& k2) { return k1 < k2; }
};

编译器会不乐意:

No matching function for call to object of type 'const CompareByLongValue<long>'

分别在 stl map 的:

    _LIBCPP_INLINE_VISIBILITY
    bool operator()(const _CP& __x, const _Key& __y) const
        // 460
        {return static_cast<const _Compare&>(*this)(__x.__cc.first, __y);}
    _LIBCPP_INLINE_VISIBILITY
    bool operator()(const _Key& __x, const _CP& __y) const
        // 463
        {return static_cast<const _Compare&>(*this)(__x, __y.__cc.first);}

// 以及 1207
if (__tree_.value_comp().key_comp()(__k, __nd->__value_.__cc.first))
ringa_leeringa_lee2803 days ago540

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 13:15:05

    The default comparison object type of map is std::less<Key>

    You can take a look at the definition of map:

    template<
        class Key,
        class T,
        class Compare = std::less<Key>,
        class Allocator = std::allocator<std::pair<const Key, T> >
    > class map;
    

    If you want to modify the default comparison behavior, you can pass in the comparison class you defined during construction: map<long, string, CompareByLongValue> amap;

    If your "map" variable is a map type without specifying a specific type, one approach is to define Compare as a template class: map<T, string, MyCompare< T > > amap;
    Then define a specialized MyCompare class.

    template <> class MyCompare<long>
    {
        bool operator()(const long& a, const long& b) const
        {
            ...
        }
    }
    

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:15:05

    Long and char* do not require custom comparison.
    Your
    template <typename T>
    std::map<const T, std::list<const T>*> map;

    Do you want to write it as
    template<typename T>
    using m_map=std::map<const T, std::list<const T>*> map;
    ?

    reply
    0
  • Cancelreply