作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试解决导致我为某些数据点创建最大和最小堆的问题。假设我有以下信息:
(10,100)
(30,120)
(14,110)
(18,200)
(20,230)
(13,49)
我想将这些数据点存储在最大和最小堆中,但我希望堆由它们的第二个值组成。但是,我仍然需要保留第一个值,因为我稍后会在程序中使用它。我怎样才能完成这个任务?始终从一组数据点中弹出最大值或始终弹出最小值,同时仍保留其他配对数据的最有效的 STL 方法是什么?
最佳答案
这看起来很简单:
#include <vector>
#include <algorithm>
int main() {
std::vector<std::pair<int, int>> values = {
{10,100},
{30,120},
{14,110},
{18,200},
{20,230},
{13,49},
};
std::make_heap(values.begin(), values.end(), [](std::pair<int, int> const & lhs, std::pair<int, int> const & rhs) {
return lhs.second < rhs.second;
});
// If you can't use c++11, then this is identical:
struct {
bool operator()(std::pair<int, int> lhs, std::pair<int, int> rhs) const {
return lhs.second < rhs.second;
}
} Compare;
std::make_heap(values.begin(), values.end(), Compare);
// And if a priority queue works:
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, decltype(Compare)> max_heap;
max_heap.push(std::make_pair(10,100));
max_heap.push(std::make_pair(30,120));
max_heap.push(std::make_pair(14,110));
max_heap.push(std::make_pair(18,200));
max_heap.push(std::make_pair(20,230));
max_heap.push(std::make_pair(13,49));
}
关于c++ - 如何使用 STL 为数据点创建最大和最小堆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622500/
我是一名优秀的程序员,十分优秀!