【问题标题】:C++11 why require comparing information twice for priority_queue constructionC ++ 11为什么需要两次比较信息来构造priority_queue
【发布时间】:2015-04-02 17:14:41
【问题描述】:

我觉得问这个问题很愚蠢,但我真的很想知道原因,然后再认真地“输入两次”我的未来代码。

例如,我从myVector(代码前定义的向量)构造一个绝对最大priority_queue:

auto comp = []( int a, int b ) { return abs(a) < abs(b); };
priority_queue<int, vector<int>, decltype(comp)> pq(comp, myVector);

comp lambda 需要填写模板(我同意,因为这个 priority_queue 实例在其生命周期中将具有该 order 属性),并且在构造函数中也需要(这让我感到困惑)。

为什么构造函数不能根据模板中的订单信息推导出订单?

【问题讨论】:

标签: templates c++11 constructor lambda priority-queue


【解决方案1】:

C++ 语言规定 lambda 具有已删除的默认构造函数,这意味着 lambda 不能是默认构造的。因此这样的代码将无法编译:

auto f1 = [](int i){return i;};
decltype(f1) f2; // ERROR: try to default-construct a lambda object "f2"

下面给出priority_queue的实现细节:

template<
     typename _ElemTy,
     typename _Container = vector<_ElemTy>,
     typename _Pred = less<typename _Container::value_type>
    >
    class priority_queue
    {
       priority_queue()
         : c(), comp() // use empty container, DEFAULT comparator
       {
       }

       priority_queue(const _Pred& p, const _Container& c)
          : cont(c), comp(p)
       {
          make_heap(cont.begin(), cont.end(), comp);
       }

       .....

如果要使用其默认构造函数并且类型 _Pred 是 lambda,则表达式 comp() 必须导致编译错误。因此,您必须使用上面的第二个构造函数,它需要一个显式提供的 lambda 对象。

【讨论】:

    猜你喜欢
    • 2014-04-16
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多