代码之家  ›  专栏  ›  技术社区  ›  Thomson

我可以用动态构造的比较器创建地图吗?

  •  1
  • Thomson  · 技术社区  · 14 年前

    我想用STL创建std::map,但是比较器依赖于一些动态值,这些值只在运行时可用。。我怎么做这个?例如,我想要看起来像 std::map<int, int, Comp(value1, value2)>

    1 回复  |  直到 14 年前
        1
  •  9
  •   Oliver Charlesworth    14 年前

    使用 functor class :

    #include <map>
    
    class Comp
    {
    public:
        Comp(int x, int y) : x(x), y(y) {}
        bool operator() (int a, int b) const { /* Comparison logic goes here */ }
    private:
        const int x, y;
    };
    
    int main()
    {
        std::map<int,float,Comp> m(Comp(value1,value2));
    }
    

    这类似于函数,但以运行时对象的形式。这意味着它可以有状态,包括运行时配置。你要做的就是超载 operator() . 如果在类定义中定义了所有成员函数体(如上所述),那么编译器可能会内联所有内容,因此性能开销可以忽略不计。

    如果你知道 value1 value2 编译时常数

    template <int x, int y>
    bool compare(int a, int b) { /* Comparison logic goes here */ }
    
    int main()
    {
        std::map<int,float,compare<value1,value2> > m;
    }