[英]How to read "std::greater<>{}" in "std::make_heap"
// min heap solution
// extract k smallest data from a min-heap of all n data points
class K_Smallest_MinHeap {
public:
K_Smallest_MinHeap(std::size_t n, std::size_t k): N(n), K(k), count(0)
{ }
void add(int value){
values.push_back(value);
}
std::vector<int> get(){
std::make_heap(values.begin(), values.end(), std::greater<>{});
std::vector<int> result;
for (std::size_t i = 0; i < K; ++i){
std::pop_heap(values.begin(), values.end(), std::greater<>{});
result.push_back(values.back());
values.pop_back();
}
return result;
}
private:
std::size_t N;
std::size_t K;
std::size_t count;
std::vector<int> values;
};
Hi everyone大家好
I do not understand the "std::greater<>{}" in std::make_heap()我不明白 std::make_heap() 中的“std::greater<>{}”
I thought the takes only two iterators begin&end?我认为只需要两个迭代器开始和结束?
"void make_heap( RandomIt first, RandomIt last );" “void make_heap(先随机,最后随机);”
Thank you for helping!感谢您的帮助!
The function std::make_heap
is overloaded for two sets of parameters function std::make_heap
为两组参数重载
template<class RandomAccessIterator>
void make_heap(RandomAccessIterator first, RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void make_heap(RandomAccessIterator first, RandomAccessIterator last,
Compare comp);
So the third parameter specifies explicitly the comparison function used to build a heap.所以第三个参数明确指定了用于构建堆的比较 function。
According to the cppreference :根据cppreference :
template< class RandomIt >
void make_heap( RandomIt first, RandomIt last );
template< class RandomIt >
constexpr void make_heap( RandomIt first, RandomIt last );
template< class RandomIt, class Compare >
void make_heap( RandomIt first, RandomIt last,
Compare comp );
template< class RandomIt, class Compare >
constexpr void make_heap( RandomIt first, RandomIt last,
Compare comp );
Constructs a max heap
in the range [first, last)
.在[first, last)
范围内构造一个max heap
。 The first version of the function uses operator<
to compare the elements, the second uses the given comparison function comp. function 的第一个版本使用operator<
来比较元素,第二个版本使用给定的比较 function 比较。
I do not understand the "std::greater<>{}" in std::make_heap()我不明白 std::make_heap() 中的“std::greater<>{}”
I thought the takes only two iterators begin&end?我认为只需要两个迭代器开始和结束?
If your make_heap
function only take two iterators, it will create a max_heap
.如果您的make_heap
function 只需要两个迭代器,它将创建一个max_heap
。
If you want to create a min_heap
, you should use operator>
to compare the elements, this is exactly what std::greater<>{}
does.如果你想创建一个min_heap
,你应该使用operator>
来比较元素,这正是std::greater<>{}
所做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.