繁体   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