简体   繁体   English

C++ STL 优先队列客户比较器不工作

[英]C++ STL priority queue customer comparator does not work

I have written almost similar code in the past and it worked (I remember vaguely).我过去写过几乎类似的代码并且它有效(我记得模糊)。 It seems that comparator is not working here??似乎比较器在这里不起作用? Any clues?有什么线索吗?

#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;
}

I was expecting it to work for pair of iterators almost as it works for integers.我期待它几乎适用于整数对的迭代器。 but it does not.但事实并非如此。

The begin() and end() iterators you get from the copy of the vector in for(auto e: A) will be invalid after the iteration ends and the temporary vector e is destroyed.for(auto e: A)中的vector副本获得的begin()end()迭代器将在迭代结束并且临时vector e被销毁后无效。

Use a reference to the inner vector instead:改为使用对内部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演示

Here's another demo where I've applied the appropriate const qualifiers.这是另一个演示,我在其中应用了适当的const限定符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM