c++中vector的pair与make_pair的使用,双关键字排序

时间:2021-08-14 04:17:17

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool strict_weak_ordering(const pair<int,string> a, const pair<int,string> b)
{
return a.first > b.first;
}
//通过运算符重载,利用sort函数实现降序排列
int main()
{

vector<pair<int, string> > vec;
//为了避免与>>运算符混淆,所以这里中间要有个空格
vec.push_back(make_pair<int, string>(5, "bingo"));
vec.push_back(make_pair<int, string>(4, "bing"));
vec.push_back(make_pair<int, string>(6, "acbingo"));
vec.push_back(make_pair<int, string>(6, "ACBingo"));
vec[3].first++;

sort(vec.begin(), vec.end(), strict_weak_ordering);
//使用迭代器
vector<pair<int, string> >::iterator it = vec.begin(), end = vec.end();
for (;it!=end;++it) cout<<it->first<<endl;
//模拟正常数组
for (int i=0;i<vec.size();i++) cout<<vec[i].second<<endl;
return 0;
}