【问题标题】:converting/constructing vector of tuples into heap将元组向量转换/构造成堆
【发布时间】:2020-10-26 11:28:56
【问题描述】:

- 建设

我构造了一个元组向量vector<tuple<int,int,int>> x。为了简单起见,我们假设它是这样构造的。

vector<tuple<int,int,int>> x;
for (int ii=0; ii < 10; ii++){
    for (int jj=0; jj < 10; jj++){
        currpeak[0] = ii + rand() % 10;
        currpeak[1] = jj + rand() % 10;
        currpeak[2] = rand() % 100;
        x.emplace_back(currpeak[0], currpeak[1], currpeak[2]);
    }
}

现在我想根据第三个元素获取最大的 n 个元组,并将它们附加到另一个变量 vector&lt;tuple&lt;int,int,int&gt;&gt; y。让我们假设n=10

- 排序

目前我正在这样做:对它们进行反向排序,然后选择前 n 个元素。

// Sort them by 3rd element
bool sortbythird_desc(const tuple<int,int,int>& a, 
            const tuple<int,int,int>& b){
    return (get<2>(a) > get<2>(b)); 
}
sort(x.begin(), x.end(), sortbythird_desc);

// Extract the top 10 elements from x and put into y
vector<tuple<int,int,int>> y;
for(int jdx =0; jdx<10; jdx++){
    int curr_peak0=get<0>(x[jdx]);
    int curr_peak1=get<1>(x[jdx]);
    int curr_peak2=get<2>(x[jdx]);
    y.emplace_back(curr_peak0, curr_peak1, curr_peak2);
}

但是由于排序,这是O(nlogn) 操作。

- 堆尝试失败

如果我可以将x 转换为堆,或者甚至从一开始就将其构造为堆:O(n) 操作。 pop_heapO(log n) 次。总共只需要O(n + log n) = O(n) 操作。但是以下失败

// Convert x to a heap
bool Comp(const tuple<int,int,int>& a){
    return get<2>(a); 
}
make_heap(x.begin(), x.end(), Comp);

错误

Severity    Code    Description Project File    Line    Suppression State
Error   C2197   'bool (__cdecl *)(const std::tuple<int,int,int> &)': too many arguments for call    Shash   C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xutility    1481    

如何修改我的代码以将 x 转换为堆,甚至首先构造 1?

【问题讨论】:

  • 看看std::nth_element函数。

标签: c++ vector tuples heap-memory


【解决方案1】:

最简单的方法是使用 () 运算符传递结构。例如

struct Comp { 
    bool operator()(const tuple<int,int,int>& a, 
            const tuple<int,int,int>& b){
           return (get<2>(a) > get<2>(b)); 
    }
};

并将其传递给make_heap

【讨论】:

  • 谢谢,它有效!请注意,我应该使用'',因为它是一个最大堆。现在,我想从头开始构建堆,我如何替换x.emplace_back(),我是否只需使用x.push_heap()
  • 您可以使用push_heap 或简单地将您的向量替换为priority_queue,但make_heap 更快。
猜你喜欢
  • 1970-01-01
  • 2015-01-25
  • 2023-04-07
  • 1970-01-01
  • 2015-09-08
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
相关资源
最近更新 更多