C++ STL 优先级队列客户比较器不起作用
C++ STL priority queue customer comparator does not work
我以前写过几乎类似的代码并且它有效(我记得很模糊)。似乎比较器在这里不起作用??有什么线索吗?
#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;
}
我原以为它对迭代器对的作用几乎与对整数的作用一样。但事实并非如此。
我以前写过几乎类似的代码并且它有效(我记得很模糊)。似乎比较器在这里不起作用??有什么线索吗?
#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;
}
我原以为它对迭代器对的作用几乎与对整数的作用一样。但事实并非如此。