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

发布于 2024-09-28 05:55:45 字数 177 浏览 0 评论 0原文

我想在 STL 中创建 std::map,但比较器依赖于一些仅在运行时可用的动态值。我怎样才能做到这一点?例如,我想要类似 std::map 的内容。 value1和value2不是这里比较的数字,它们是某种配置数字。

I want to create std::map in STL, but the comparer depends some dynamic value which is available only at runtime.. How can I make this? For example, I want something looks like std::map<int, int, Comp(value1, value2)>. value1 and value2 are not the compared number here, they are some kind of configuration numbers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里°也失望 2024-10-05 05:55:45

使用函子类

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

Use a 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));
}

This is like a function, but in the form of a runtime object. This means it can have state, which includes runtime configuration. All you have to do is overload operator(). If you define all the member-function bodies in the class definition (as above), then the compiler will probably inline everything, so there'll be negligible performance overhead.

If you know value1 and value2 at compile-time (i.e. if they are compile-time constants), you could use a function template instead:

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文