【C++】用STL heap寻找最小的k个值

思路:
建立一个最大堆,如果新添加的元素小于堆顶元素,pop_heap出去堆顶元素,然后push_heap进去新添加的元素;否则,什么也不用做。

同理,用STL heap寻找最小的k个值则需要建立最小堆,操作正好反过来。

注意:make_heap、pop_heap以及push_heap中的_Compare参数要保持一致,否则会失败。


代码实现(以“寻找最小的10个值”为例):

#include<iostream>
#include<vector>
#include<algorithm>
#include <time.h> 
using namespace std;


int RandomInRange(int start, int end) {
	if (start >= end) {
		throw new std::exception("error");
	}

	return rand() % (end - start + 1) + start;
}

int main()
{	
	vector<int> vec(10, INT_MAX);
	vector<int> vec2;
	int t;

	srand((unsigned)time(NULL));

	make_heap(vec.begin(), vec.end()); // 建立一个最大堆

	for (int i = 0; i < vec.size()*10; ++i) {
		t = RandomInRange(1,1000); // 随机生成1~1000范围的数字
		vec2.push_back(t);

		// 选出最小的k个数
		if (t < vec[0]) {
			pop_heap(vec.begin(), vec.end()); // 把顶端元素放到了数组的最后
			vec[vec.size() - 1] = t; 
			push_heap(vec.begin(), vec.end()); // 把数组最后的元素调整到合适位置
		}
	}
	
	sort(vec2.begin(), vec2.end());
	
	return 0;
}


参考:
https://blog.csdn.net/qq_29630271/article/details/66478256

原创文章 299 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zxc120389574/article/details/106117367
今日推荐