Очередь приоритета stl по умолчанию - максимальная (функция Top возвращает наибольший элемент).
Скажем, для простоты, что это очередь приоритетов значений int.
Очередь приоритета stl по умолчанию - максимальная (функция Top возвращает наибольший элемент).
Скажем, для простоты, что это очередь приоритетов значений int.
В качестве функции сравнения используйте std::greater
:
std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
Одним из способов было бы определить подходящий компаратор, с которым можно работать в обычной очереди приоритетов, чтобы его приоритет менялся:
#include <iostream>
#include <queue>
using namespace std;
struct compare
{
bool operator()(const int& l, const int& r)
{
return l > r;
}
};
int main()
{
priority_queue<int,vector<int>, compare > pq;
pq.push(3);
pq.push(5);
pq.push(1);
pq.push(8);
while ( !pq.empty() )
{
cout << pq.top() << endl;
pq.pop();
}
cin.get();
}
Который выдавал бы 1, 3, 5, 8 соответственно.
Некоторые примеры использования очередей приоритетов через STL и Реализации Sedgewick приведены здесь.
Третий параметр шаблона для priority_queue
- это компаратор. Установите для него greater
.
например.
std::priority_queue<int, std::vector<int>, std::greater<int> > max_queue;
Вам понадобится #include <functional>
для std::greater
.
В С++ 11 вы также можете создать псевдоним для удобства:
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
И используйте его следующим образом:
min_heap<int> my_heap;
Вы можете сделать это несколькими способами:
1. Используя greater
в качестве функции сравнения:
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<< " ";
}
return 0;
}
2. Вставка значения путем изменения их знака (используя минус (-) для положительного числа и используя плюс (+) для отрицательного числа:
int main()
{
priority_queue<int>pq2;
pq2.push(-1); //for +1
pq2.push(-2); //for +2
pq2.push(-3); //for +3
pq2.push(4); //for -4
while(!pq2.empty())
{
int r = pq2.top();
pq2.pop();
cout<<-r<<" ";
}
return 0;
}
3. Использование пользовательской структуры или класса:
struct compare
{
bool operator()(const int & a, const int & b)
{
return a>b;
}
};
int main()
{
priority_queue<int,vector<int>,compare> pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<<" ";
}
return 0;
}
4. Используя пользовательскую структуру или класс, вы можете использовать priority_queue в любом порядке. Предположим, мы хотим сортировать людей в порядке убывания в соответствии с их зарплатой и, если связывать их по своему возрасту.
struct people
{
int age,salary;
};
struct compare{
bool operator()(const people & a, const people & b)
{
if(a.salary==b.salary)
{
return a.age>b.age;
}
else
{
return a.salary>b.salary;
}
}
};
int main()
{
priority_queue<people,vector<people>,compare> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Тот же результат может быть получен при перегрузке оператора:
struct people
{
int age,salary;
bool operator< (const people & p)const
{
if(salary==p.salary)
{
return age>p.age;
}
else
{
return salary>p.salary;
}
}};
В основной функции:
priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Один из способов решения этой проблемы - надавить отрицательный результат каждого элемента в priority_queue, так что наибольший элемент станет наименьшим элементом. Во время создания поп-операции возьмите отрицание каждого элемента.
#include<bits/stdc++.h>
using namespace std;
int main(){
priority_queue<int> pq;
int i;
// push the negative of each element in priority_queue, so the largest number will become the smallest number
for (int i = 0; i < 5; i++)
{
cin>>j;
pq.push(j*-1);
}
for (int i = 0; i < 5; i++)
{
cout<<(-1)*pq.top()<<endl;
pq.pop();
}
}
На основе выше всех ответов я создал пример кода для создания очереди приоритетов. Примечание. Он работает с компиляторами С++ 11 и выше.
#include <iostream>
#include <vector>
#include <iomanip>
#include <queue>
using namespace std;
// template for prirority Q
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
template<class T> using max_heap = priority_queue<T, std::vector<T>>;
const int RANGE = 1000;
vector<int> get_sample_data(int size);
int main(){
int n;
cout << "Enter number of elements N = " ; cin >> n;
vector<int> dataset = get_sample_data(n);
max_heap<int> max_pq;
min_heap<int> min_pq;
// Push data to Priority Queue
for(int i: dataset){
max_pq.push(i);
min_pq.push(i);
}
while(!max_pq.empty() && !min_pq.empty()){
cout << setw(10) << min_pq.top()<< " | " << max_pq.top() << endl;
min_pq.pop();
max_pq.pop();
}
}
vector<int> get_sample_data(int size){
srand(time(NULL));
vector<int> dataset;
for(int i=0; i<size; i++){
dataset.push_back(rand()%RANGE);
}
return dataset;
}
Вывод над кодом
Enter number of elements N = 4
33 | 535
49 | 411
411 | 49
535 | 33
Мы можем сделать это несколькими способами.
int main()
{
priority_queue<int, vector<int>, greater<int> > pq;
pq.push(40);
pq.push(320);
pq.push(42);
pq.push(65);
pq.push(12);
cout<<pq.top()<<endl;
return 0;
}
struct comp
{
bool operator () (int lhs, int rhs)
{
return lhs > rhs;
}
};
int main()
{
priority_queue<int, vector<int>, comp> pq;
pq.push(40);
pq.push(320);
pq.push(42);
pq.push(65);
pq.push(12);
cout<<pq.top()<<endl;
return 0;
}