把这两个放在一起比较,主要是针对把元素全部插入后,求最值的情况,而不是中间还会有值插入的情况。
测试平台是VS2012,比较后发现,Release模式下,priority_queue快于vector+sort的模式,而在Debug模式下正好相反。
测试代码:
#include <iostream>
#include <vector>
#include <queue>
#include <ctime>
#include <string>
#include <memory>
#include <cstdlib>
#define MAX 1000000
using namespace std;
struct Puzzle{
string puzzle;
short blank;
unsigned short g;
unsigned short f;
bool site;
bool sub[4];
unsigned short sf;
shared_ptr<Puzzle> pre;
};
typedef shared_ptr<Puzzle> PUZZLE;
struct cmp{
bool operator() (PUZZLE p1, PUZZLE p2)
{
return p1->f > p2->f;
}
};
bool cmp1(PUZZLE p1, PUZZLE p2)
{
return p1->f < p2->f;
}
vector<PUZZLE> vp;
vector<int> vi;
priority_queue<PUZZLE, vector<PUZZLE>, cmp> pq;
int main(){
double stime, ftime;
PUZZLE node;
srand(time(NULL));
vi.reserve(MAX);
for(size_t i=0; i<MAX; i++) vi.push_back(rand()%65535);
stime = clock();
for(size_t i=0; i<MAX; i++)
{
node = PUZZLE(new Puzzle);
node->f = vi[i];
vp.push_back(node);
}
sort(vp.begin(), vp.end(), cmp1);
ftime = clock();
cout<<""<<(ftime-stime)/CLOCKS_PER_SEC<<"s"<<endl;
stime = clock();
for(size_t i=0; i<MAX; i++)
{
node = PUZZLE(new Puzzle);
node->f = vi[i];
pq.push(node);
}
ftime = clock();
cout<<""<<(ftime-stime)/CLOCKS_PER_SEC<<"s"<<endl;
if(vp.front()->f == pq.top()->f) cout<<"right"<<endl;
else{
cout<<"wrong"<<endl;
cout<<vp.front()->f<<endl;
cout<<pq.top()->f<<endl;
}
system("PAUSE");
return 0;
}
测试结果(Release模式):
-100000个元素
- 1000000个元素
Debug模式可以自己试一下,结果是反过来的,vector+sort更快,而且两者差距很大。