priority_queue 、 make_heap 默认都是递减的方式 ,less<T>调整堆的大小的。
<queue>
- priority_queue
- https://zh.cppreference.com/w/cpp/container/priority_queue
注意:优先级队列默认是先出大的元素,也就是 less ,使出现递减序列。
int main()
{
vector<int> arr = { 3,2,1,9,8,7,4,5,6 };
创建优先级队列:
a_默认是less的,也就是递减序列,出队时先出大的数: // 6.5.4.3.2.1
// 默认 <int,vector<T>,less<T> > 递减序列,第一个出队的是最大元素
priority_queue<int> pq_l(arr.begin(), arr.end());
// 等价于
priority_queue<int> pq_l(arr.begin(), arr.end(), less<int>());
priority_queue<int, vector<int>, less<int> > pq_l(arr.begin(), arr.end());
priority_queue<int, vector<int>, less<int> > pq_l(arr.begin(), arr.end(), less<int>());
b_使用greater创建递增序列,即出队时先出小的数: // 1,2,3,4,5,6
// 注意:不能使用 greater<int>(), 因为模板参数默认是 less<int>()
// priority_queue<int> pq_g(arr.begin(), arr.end(), greater<int>());
priority_queue<int, vector<int>, greater<int>> pq_g(arr.begin(), arr.end(), greater<int>());
// 等价于
priority_queue<int, vector<int>, greater<int>> pq_g(arr.begin(), arr.end());
c_创建一个空的队列,然后使用push插入:
priority_queue<int> q;
使用优先级队列:
push://插入元素,并对底层容器排序
emplace://原位构造元素并排序底层容器
pop://删除队首元素
swap://交换内容
}
<algorithm>
- make_heap
- https://zh.cppreference.com/w/cpp/algorithm/make_heap
- 在容器范围内,就地建堆,保证最大值在所给范围的最前面,其他值的位置不确定
- pop_heap
- https://zh.cppreference.com/w/cpp/algorithm/pop_heap
- 将堆顶(所给范围的最前面)元素移动到所给范围的最后,并且将新的最大值置于所给范围的最前面。即[fist, last-1] 任然为有效的堆。
- 注意:pop_heap将元素移动到末尾后,默认是按照大根堆的方式调整的,即将次大值调整到首部。(使用时注意第三个参数的运用)
- push_heap
- https://zh.cppreference.com/w/cpp/algorithm/push_heap
- 当已建堆的容器范围内有新的元素插入末尾后,应当调用push_heap将该元素插入堆中。
注意:默认是以大根堆进行调整。默认是以less ,即递减的序列。
// pop_heap
int main()
{
vector<int> vec{ 6 ,5,7,3,1,2,4,100 };
make_heap(vec.begin(), vec.end(), greater<int>()); // 1,2,3,4,5,6 ..
cout << vec.front() << endl; // root 元素,最小值
pop_heap(vec.begin(), vec.end()); // 默认是大根调整,
// 100 ...... 1
cout << vec.front() << " ... " << vec.back() << endl;
pop_heap(vec.begin(), vec.end(), greater<int>()); // 将手元素移动末尾,将其他元素调整为小根堆
// 原始: 100 , .... , 1
// 移动: ___ , .... , 1 , 100 fist -> last
// 调整: 1 , .... , 100 [fist, last - 1] 调整
cout << vec.front() << " ... " << vec.back() << endl;
return 0;
}
// push_heap
int main()
{
std::vector<int> v{ 3, 1, 4, 1, 5, 9 };
std::make_heap(v.begin(), v.end()); // 建立大根堆
std::cout << "v: ";
for (auto i : v) std::cout << i << ' '; // 输出
std::cout << '\n';
v.push_back(6); // 尾部,插入,新元素
std::cout << "before push_heap: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
std::push_heap(v.begin(), v.end()); // 每次 尾部插入 ,都需要调用 push(begin(), end()) 进行调整
std::cout << "after push_heap: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
}
/*
v: 9 5 4 1 1 3
before push_heap: 9 5 4 1 1 3 6
after push_heap: 9 5 6 1 1 3 4
*/