【问题标题】:How to use default comparator in own class?如何在自己的类中使用默认比较器?
【发布时间】:2015-03-11 11:25:58
【问题描述】:

我想创建自己的数据容器,例如STL-containers

template <class priorityType = size_t, class Compare = std::less<priorityType>>
class task_queue
{
public:
    task_queue(Compare c = Compare())
    {

    }

private:
    std::priority_queue<priorityType, std::vector<priorityType>, Compare> tasks_id;
};

int main() {
    struct foo
    {
        int a;
    };

    struct foo_compare
    {
        bool operator()(const foo& lhs, const foo& rhs) const {
            return lhs.a < rhs.a;
        }
    };

    task_queue<foo, foo_compare> queue{ foo_compare() };
}

我想在tasks_id PQ 中使用传递给构造函数的comparator。我该怎么做?

【问题讨论】:

  • 如果你在构造函数中传递一个比较操作符,你将不会得到比较的编译时绑定,即你的代码效率会降低。
  • @ErikAlapää,但 STL 容器以这种方式使用这些东西。
  • 一般来说,好的 C++ 代码,包括 STL,尽可能尝试使用编译时绑定。这就是为什么 C++ 中的 std::sort 比 C 快速排序快的原因之一。 (C++ 排序使用编译时限制比较,而普通 C 快速排序使用函数指针)。
  • _ -1:阅读 priority_queue 文档的简单失败。
  • @LightnessRacesinOrbit,PQ 只是示例,并非实际应用。

标签: c++ c++11 stl containers comparator


【解决方案1】:

直接拨打constructor即可。

task_queue(Compare c = Compare()) : tasks_id(c)
{

}

【讨论】:

  • @ForEveR,如果在这样的比较器中需要my_class,但没有像PQ这样的结构呢?比如my_class有方法,比较它的参数?
  • @Denis 将 Compare 对象存储在类中,在 c-tor 中正确构造它,在需要时使用它。
【解决方案2】:

你只需要调用它:

c(valuetocompare1, valuetocompare2);

就这么简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2014-10-25
    • 2019-08-22
    相关资源
    最近更新 更多