【发布时间】: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