c++ - 我可以使用动态构建的比较器创建 map 吗?

标签 c++ stl

我想在 STL 中创建 std::map,但比较器依赖于一些仅在运行时可用的动态值。我该怎么做?例如,我想要看起来像 std::map<int, int, Comp(value1, value2)> 的东西. value1 和 value2 不是这里比较的数字,它们是某种配置数字。

最佳答案

使用 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()。如果您在类定义中定义所有成员函数体(如上所述),那么编译器可能会内联所有内容,因此性能开销可以忽略不计。

如果您在编译时知道 value1value2(即如果它们是编译时常量),您可以使用函数模板代替:

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;
}

关于c++ - 我可以使用动态构建的比较器创建 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3966352/

相关文章:

c++ - 使用std::map应该是确定性的吗?

c++ - MPI:Waitany 对 ibcast 调用没有反应

c++ - 如何在 NCurses/PdCurses 中实现滚动或列表框? ( C )

c++ - 一些 STL 容器的 std::allocator 不匹配

c++ - 在学习 BOOST 替代品之前,我应该精通 STL 库吗?

c++ - 在 vector : better to store the object or a pointer to it? 中存储对象

c++ - 用 g++/bison/boost::variant 编写的解析器编译速度很慢

c++ - 错误: ‘void*’ is not a pointer-to-object type

c++ - 从 begin() 而不是 cbegin() 获取 const_iterator

c++ - STL 列表添加和删除所选元素