empty()
#include <iostream>
#include <queue>
int main ()
{
std::priority_queue<int> mypq;
int sum (0);
for (int i=1;i<=10;i++) mypq.push(i);
while (!mypq.empty())
{
sum += mypq.top();
mypq.pop();
}
std::cout << "total: " << sum << '
';
return 0;
}
size()
#include <iostream>
#include <queue>
int main ()
{
std::priority_queue<int> myints;
std::cout << "0. size: " << myints.size() << '
';
for (int i=0; i<5; i++) myints.push(i);
std::cout << "1. size: " << myints.size() << '
';
myints.pop();
std::cout << "2. size: " << myints.size() << '
';
return 0;
}
top()
#include <iostream>
#include <queue>
int main ()
{
std::priority_queue<int> mypq;
mypq.push(10);
mypq.push(20);
mypq.push(15);
std::cout << "mypq.top() is now " << mypq.top() << '
';
return 0;
}
push()
#include <iostream>
#include <queue>
int main ()
{
std::priority_queue<int> mypq;
mypq.push(30);
mypq.push(100);
mypq.push(25);
mypq.push(40);
std::cout << "Popping out elements...";
while (!mypq.empty())
{
std::cout << ' ' << mypq.top();
mypq.pop();
}
std::cout << '
';
return 0;
}
pop()
#include <iostream>
#include <queue>
int main ()
{
std::priority_queue<int> mypq;
mypq.push(30);
mypq.push(100);
mypq.push(25);
mypq.push(40);
std::cout << "Popping out elements...";
while (!mypq.empty())
{
std::cout << ' ' << mypq.top();
mypq.pop();
}
std::cout << '
';
return 0;
}
以下是 c++11版 才有的
emplace()直接加入操作
#include <iostream>
#include <queue>
#include <string>
int main ()
{
std::priority_queue<std::string> mypq;
mypq.emplace("orange");
mypq.emplace("strawberry");
mypq.emplace("apple");
mypq.emplace("pear");
std::cout << "mypq contains:";
while (!mypq.empty())
{
std::cout << ' ' << mypq.top();
mypq.pop();
}
std::cout << '
';
return 0;
}
swap()
#include <iostream>
#include <queue>
int main ()
{
std::priority_queue<int> foo,bar;
foo.push (15); foo.push(30); foo.push(10);
bar.push (101); bar.push(202);
foo.swap(bar);
std::cout << "size of foo: " << foo.size() << '
';
std::cout << "size of bar: " << bar.size() << '
';
return 0;
}
小根堆的写法(直接定义时默认是大根堆)
#include <iostream>
#include <queue>
using namespace std;
int main ()
{
priority_queue< int, vector<int>, greater<int> > mypq;
mypq.push(10);
mypq.push(20);
mypq.push(15);
cout << "mypq.top() is now " << mypq.top() << '
';
return 0;
}