簡體   English   中英

如何將優先隊列中的對推送到二維數組中?

[英]How to push pair from priority queue into a 2D array?

我正在做一個 leetcode 問題,我需要返回一個二維結果數組。 但是我為此使用了優先級隊列,並且無法將元素移動到二維數組。 我無法為此提出語法。 當我嘗試將這對推入二維數組時,push_back() 不起作用。 這是問題的鏈接

代碼 -


    class Solution {
public:
    vector<vector<int>> kClosest(vector<vector<int>>& p, int k) {
        vector<vector<int>>closest;
        //pairp;
       priority_queue<pair<int,pair<int,int>>>heap;
        
        for(int i = 0; i < p.size(); i++){
            
            heap.push({p[i][0] * p[i][0] + p[i][1]*p[i][1],
                       {p[i][0],p[i][1]}});
                      
                      
        }
        
        if(heap.size() > k){
            heap.pop();
        }
        
        
        while(heap.size() > 0){
            pair<int,int>ptr = heap.top().second;
            //want to add the statement to copy elements to closest[][] here
            heap.pop();
        }
    return closest;
    }

};

添加時出現錯誤消息,最接近.push_back(ptr);

第 22 行:字符 21:錯誤:沒有匹配的成員 function 用於調用“push_back”

        closest.push_back(ptr);
        ~~~~~~~~^~~~~~~~~

/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1184:7:注意:候選 function 不可行:沒有已知的從 'pair<int, int>' 到 'const std::vector<std::vector<int, std::allocator>, std::allocator<std::vector<int,第一個參數 push_back(const value_type& __x) ^ /usr/bin/../lib/gcc /x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1200:7:注意:候選 function 不可行:從 'pair 沒有已知的轉換<int, int>' 到 'std::vector<std::vector<int, std::allocator>, std::allocator<std::vector<int, std::allocator>>>::value_type' (又名 'std::vector<int, std::allocator>') 用於第一個參數 push_back(value_type&& __x) ^ 1 產生錯誤。

// if closet should be your answer then its size will be k
/* Here we tell how many rows
    the 2D vector is going to have. And Each row will contain a vector of size 2 */
int row = k;
vector<vector<int>>closest(row, vector<int>(2));
int index = 0;
while(heap.size() > 0) {
    pair<int,int>ptr = heap.top().second;

    //Added [want to add] the statement to copy elements to closest[][] here
    closet[index][0] = ptr.first;
    closet[index][1] = ptr.second;
    index++;

    heap.pop();
}

另外,我想更正您彈出元素的代碼。 您應該檢查 while 條件而不是 'if' 條件。 'if' 條件只會彈出一次。 如下:

while(heap.size() > k){
    heap.pop();
}

// 如果你想使用 push_back 那么你可以這樣寫:

// 還按照上面的建議更正代碼,將“if”條件替換為“while”

vector<vector<int>>closest(k);
int index = 0;
while(heap.size() > 0){
    pair<int,int>ptr = heap.top().second;
    closest[index].push_back(ptr.first);
    closest[index].push_back(ptr.second);
    index++;
    heap.pop();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM