我想在 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()
。如果您在类定义中定义所有成员函数体(如上所述),那么编译器可能会内联所有内容,因此性能开销可以忽略不计。
如果您在编译时知道 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;
}
关于c++ - 我可以使用动态构建的比较器创建 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3966352/