ตัวเปรียบเทียบลูกค้าคิวลำดับความสำคัญ C ++ STL ไม่ทำงาน

ฉันเคยเขียนโค้ดที่คล้ายกันเกือบในอดีตและใช้งานได้ (ฉันจำได้ไม่ชัดเจน) ดูเหมือนว่าตัวเปรียบเทียบไม่ทำงานที่นี่?? มีเบาะแสอะไรบ้าง?

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

ฉันคาดหวังว่ามันจะใช้งานได้กับตัววนซ้ำคู่หนึ่งเกือบจะใช้งานได้กับจำนวนเต็ม แต่มันไม่ได้


person Alan Turing    schedule 12.08.2020    source แหล่งที่มา
comment
ใช้งานไม่ได้ แสดงออกอย่างไร?   -  person Ted Lyngmo    schedule 12.08.2020
comment
ฉันคาดหวังให้คิวสำคัญในการให้หมายเลขแก่ฉัน.. กำลังให้ที่อยู่บางส่วนแก่ฉัน ดูเหมือนว่าตัวเปรียบเทียบลูกค้าทำงานไม่ถูกต้อง ฉันพยายามพิมพ์ a.first และ b.first แต่มันพิมพ์ a.first ทั้งสองครั้ง   -  person Alan Turing    schedule 12.08.2020
comment
การจดจำอย่างคลุมเครือว่าสิ่งที่ เกือบ ได้ผลในอดีตนั้นไม่ใช่ข้อบ่งชี้ที่ชัดเจนถึงการทำงานหรือความคล้ายคลึงกัน   -  person molbdnilo    schedule 12.08.2020
comment
คุณอาจต้องการ std::merge   -  person Kenny Ostrom    schedule 12.08.2020


คำตอบ (1)


ตัววนซ้ำ begin() และ end() ที่คุณได้รับจาก สำเนา ของ vector ใน for(auto e : A) จะไม่ถูกต้องหลังจากการวนซ้ำสิ้นสุดลง และ 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());
}

สาธิต

นี่เป็นการสาธิตอีกรายการหนึ่งที่ฉันใช้ตัวระบุ const ที่เหมาะสม

person Ted Lyngmo    schedule 12.08.2020
comment
@Const แน่นอน! ฉันจะแก้ไขปัญหานั้น! ขอบคุณ! (และชื่อที่ดีด้วย) แก้ไข: แก้ไขแล้ว! - person Ted Lyngmo; 12.08.2020
comment
ใช่... ฉันชอบ const ;) - person Const; 12.08.2020
comment
ขอบคุณ @TedLyngmo การใช้ e โดยการอ้างอิงแก้ไขปัญหาได้ !! - person Alan Turing; 14.08.2020
comment
@AlanTuring ดีใจที่ได้! ไชโย! - person Ted Lyngmo; 14.08.2020