Search code examples
c++comparatorpriority-queue

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.


Solution

  • 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.

    Use a reference to the inner vector instead:

    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.