【问题标题】:How to push pair from priority queue into a 2D array?如何将优先队列中的对推送到二维数组中?
【发布时间】:2023-04-09 22:53:02
【问题描述】:

我正在做一个 leetcode 问题,我需要返回一个二维结果数组。但是我为此使用了优先级队列,并且无法将元素移动到二维数组。我无法为此提出语法。 当我尝试将这对推入二维数组时,push_back() 不起作用。 这是problem的链接

代码-


    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:错误:没有匹配的成员函数调用“push_back”

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

/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1184:7 : 笔记: 候选函数不可行:没有从 'pair' 到 'const 的已知转换 std::vector<:vector std::allocator>, std::allocator<:vector std::allocator>>>::value_type' (又名 'const std::vector') 用于第一个参数 push_back(const value_type& __x) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1200:7:注意:候选函数不可行:没有已知的从 'pair' 到 'std::vector<:vector std::allocator>, std::allocator<:vector std ::allocator>>>::value_type'(又名 'std::vector')用于第一个参数 push_back(value_type&& __x) ^ 产生了 1 个错误。

【问题讨论】:

  • closest 是一个 int 向量的向量。您不能将pair&lt;int,int&gt; 推入其中,因为它需要vector&lt;int&gt;。也许你想把你的对转换成一个向量,也许你想要别的东西;你的问题还不是很清楚。如果heap 包含元素{2, {1,0}},您希望closest 在插入该元素后看起来像什么?

标签: c++ arrays priority-queue std-pair


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多