我可以使用动态构造的比较器创建地图吗?
我想在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用函子类:
这就像一个函数,但采用运行时对象的形式。这意味着它可以有状态,其中包括运行时配置。您所要做的就是重载
operator()
。如果您在类定义中定义了所有成员函数体(如上所述),那么编译器可能会内联所有内容,因此性能开销可以忽略不计。如果您在编译时知道
value1
和value2
(即,如果它们是编译时常量),则可以改用函数模板:Use a functor class:
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
andvalue2
at compile-time (i.e. if they are compile-time constants), you could use a function template instead: