C++最小堆/最大堆的構造

C++最小堆/最大堆的構造

// 使用 priority_queue, #include <queue>
// priority_queue 優先隊列,底層數據結構就是紅黑樹。默認是降序排列,所以本身就是一個最大堆。

#include <iostream>
#include <queue>

using namespace std;

struct node
{
	string name;
	int value;
	node(string name_, int value_) : name(name_), value(value_) {}
	friend bool operator < (const node& a, const node& b)
	{
		return a.value < b.value;  // 定義排序
	} 
};
int main(int argc, char* argv[])
{
	priority_queue<node> p_qu{};  // 
	/*
	do something
	*/
	return 0;
}
// 或者
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

struct node
{
	string name;
	int value;
	node(string name_, int value_) : name(name_), value(value_) {}
};
struct compare
{
	bool operator()(const node& a, const node& b)
	{
		return a.value < b.value;
	}
};
int main(int argc, char* argv[])
{
	priority_queue<node, vector<node>, compare> p_qu{};
	return 0;
}
// 使用 multiset
#include <iostream>
#include <set>
#include <vector>

using namespace std;

struct node
{
	int index;
	int value;
	node(int i, int j) : index(i), value(j) {}
};

struct compare
{
	bool operator()(const node& a, const node& b)  // 參數一定是const
	{
		return a.value < b.value;  // 升序
		// return a.value > b.value;  // 降序
	}
};

int main()
{
	vector<int> nums{2, 8, 4, 1, 9, 5};
	// 最小堆
	multiset<node, compare> m_set{};  // set和multiset底層都是紅黑樹。compare是自定義的排序(自定義爲升序),所以m_set是一個最小堆。
	for (int i = 0; i < nums.size(); i++)
	{
		node n(i, nums[i]);
		m_set.insert(n);
	}
	for (auto it = m_set.begin(); it != m_set.end(); it++)
		cout << it->value << endl;
	return 0;
}

// set會自動去重,multiset允許重複數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章