【问题标题】:C++ STL priority queue customer comparator does not workC++ STL 优先级队列客户比较器不起作用
【发布时间】:2020-08-12 12:00:44
【问题描述】:

我过去写过几乎类似的代码并且它工作(我记得模糊)。似乎比较器在这里不起作用?有什么线索吗?

#include<iostream>
#include<vector>
#include<queue>
#include<iterator>
#include<algorithm>
using namespace std;

    typedef pair<vector<int>::iterator,vector<int>::iterator> PR;
    struct CompareFn{
        bool operator()(const PR& a, const PR& b){
            //cout<<"a and b first: "<<*(a.first)<<" "<< *(b.first)<<endl;
            return *a.first > *b.first;
        }
    };

vector<int> mergeKSortedArrays(vector<vector<int>> &A) {  
vector<int> result;
    
    priority_queue<PR, vector<PR>, CompareFn> PQ;
    for(auto e:A){  
        if(e.size()>0) PQ.push({e.begin(),e.end()});
    }

    while(PQ.size()>0) {
        PR tmp = PQ.top(); PQ.pop();
        auto cur=tmp.first;
        auto lst=tmp.second;
        result.emplace_back (*cur);
        if((++cur)!=lst) PQ.push({cur,lst});
    }
return result;
}


int main() { 
vector<vector<int>> v= {{2,3,8,10},{1,4,12},{4,5,8}};
 vector<int> result = mergeKSortedArrays(v);
 copy(result.begin(),result.end(), ostream_iterator<int>(cout," "));
 return 0;
}

我期待它可以像处理整数一样用于迭代器对。但事实并非如此。

【问题讨论】:

  • 不起作用”如何表现出来?
  • 我期待它的优先队列给我数字。它给了我一些地址。客户比较器似乎无法正常工作。我尝试打印 a.first 和 b.first 但两次都打印 a.first。
  • 模糊地记得过去几乎类似的东西有效并不能很好地表明有效或相似。
  • 你可能想要 std::merge。

标签: c++ comparator priority-queue


【解决方案1】:

您从for(auto e : A) 中的vector副本 中获得的begin()end() 迭代器将在迭代结束后无效,临时的vector e 是销毁。

改为使用对内部vector 的引用:

for(auto& e : A) { // "auto& e" makes "e" a reference to the existing vector
    if(e.size()>0) PQ.emplace(e.begin(), e.end());
}

demo

这是另一个demo,我在其中应用了适当的const 限定符。

【讨论】:

  • @Const 确实!我会解决的!谢谢! (而且,好名字顺便说一句)编辑:固定!
  • 是的,...我喜欢const。 ;)
  • 感谢@TedLyngmo,通过引用使用e 解决了这个问题!!
  • @AlanTuring 很高兴它做到了!干杯!
猜你喜欢
  • 2016-04-13
  • 2016-03-10
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
相关资源
最近更新 更多