对于优先级队列priority_queue,注意默认的是less函数,优先级队列是大数在队列头,若想要小数在队列头部,需要greater。
但是对于自定义的二元谓词函数应该是重载()运算符,或者使用仿函数
struct cmp
{
bool operator()(pair<int, int>& a, pair<int, int>& b)
{
if (a.first == b.first)
return a.second > b.second;
else
return a.second < b.second;
}
};
int main()
{
priority_queue<pair<int, int>, vector<pair<int,int>>, cmp> que;
}
对于set应该这么写:
需要注意的是set默认使用less得到的将是从小到大的排列,使用great得到的是从大到小的排列,这个和优先级队列相反
struct cmp
{
bool operator() (int a, int b)
{
if (a < b)
return true;
else
return false;
}
};
int main()
{
set<int, cmp> ss;
multiset<int, greater<int>> ms;
for (int i = 0; i < 10; i++)
{
ss.insert(i);
ms.insert(i);
ms.insert(i + 1);
}
for (int i : ss)
cout << i << " ";
cout << endl;
for (int i : ms)
cout << i << " ";
cout << endl;
system("pause");
}
对于map呢?
需要注意的是cmp函数是const函数,所以后面的const是必须要的
参考这个博客
[C/C++]map自定义比较函数
struct cmp
{
bool operator() (int a, int b) const
{
if (a < b)
return true;
else
return false;
}
};
int main()
{
map<int, int,cmp> mp;
multimap<int, int,cmp> mmp;
for (int i = 0; i < 10; i++)
mp[i] = i;
for (auto i : mp)
cout << i.first << " ";
cout << endl;
system("pause");
}
对于multimap则有点复杂,参考这个博客C++的multimap自定义key值
主要就是重载小于<运算符,注意这里实在类中重载的
#include<iostream>
#include<stdio.h>
#include<map>
class A
{
public:
A(int a) :a_(a) {}
bool operator<(A BObj) const {
return a_<BObj.a_;
}
private:
int a_;
};
int main()
{
std::multimap<A, std::string> mapTest;
mapTest.insert(std::make_pair(A(4), "zsy"));
mapTest.insert(std::make_pair(A(2), "qwe"));
mapTest.insert(std::make_pair(A(1), "asd"));
mapTest.insert(std::make_pair(A(3), "qwe"));
auto it = mapTest.begin();
for (; it != mapTest.end(); it++)
{
printf("%s\n", it->second.c_str());
}
system("pause");
return 0;
}