1.pair在头文件utility中,可以有pair定义动态数组进行排序,pair中内置了<的默认排序方式,即对first进行默认的升序排序,也可以通过sort函数自定义排序方式
pair的vector类型
bool strict_weak_ordering(const std::pair<int,std::string>a,const std::pair<int,std::string>b)
{ return a.first < b.first; }
int main()
{
using namespace std;
vector<pair<int, string> > vec;
vec.push_back(make_pair<int, string>(5, "hello"));
vec.push_back(make_pair<int, string>(4, "hell"));
vec.push_back(make_pair<int, string>(6, "hello,"));
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->second<<endl;
}
pair的基础操作 https://blog.csdn.net/sunpeishuai/article/details/81239123
#include <utility>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
typedef pair<int, int> P;
const int N = 5;
pair<int, int> items[N];
bool cmp(const P &a, const P&b)
{
if (a.first < b.first)
return true;
else return false;
}
int main()
{
srand(time(NULL));
for (int i = 0; i < N; i++)
items[i] = make_pair(rand(), i + 1);
cout << "before sorted:" << endl;
for (int i = 0; i < N; i++)
cout << "(" << items[i].first << ", " << items[i].second << ")\t";
cout << endl;
sort(items, items + N, cmp);
cout << "\nafter sorted:" << endl;
for (int i = 0; i < N; i++)
cout << "(" << items[i].first << ", " << items[i].second << ")\t";
cout << endl;
cin.get();
return 0;
}