一、pair对组
成对出现的数据,利用对组可以返回两个数据
1、创建方式
1) pair
2) pair
- void test01()
-
- {
-
- pair
int>p("张三", 18); -
- cout << "姓名:" << p.first << " 年龄:" << p.second << endl;
-
- pair
int>p1 = make_pair("张三", 18); -
- cout << "姓名:" << p1.first << " 年龄:" << p1.second << endl;
-
- }

二、set容器的排序
默认从小到大,掌握如何改变其排序规则
利用仿函数,改变其排序规则
- void printSet(set<int>&s)
-
- {
-
- for (set<int>::iterator it = s.begin(); it != s.end(); it++)\
-
- {
-
- cout << *it << " ";
-
- }
-
- cout << endl;
-
- }
-
- //仿函数
-
- class Compare {
-
- public:
-
- bool operator()(int v1, int v2) //重载()
-
- {
-
- return v1 > v2;
-
- }
-
- };
-
-
-
- void test02()
-
- {
-
- set<int>s1;
-
- s1.insert(10);
-
- s1.insert(20);
-
- s1.insert(5);
-
- s1.insert(20);
-
- printSet(s1);//5 10 20 自动排序 且去除重复元素
-
- //指定排序规则 从大到小
-
- set<int,Compare>s2;
-
- s2.insert(10);
-
- s2.insert(20);
-
- s2.insert(5);
-
- s2.insert(20);
-
- //单独写一个迭代器遍历
-
- for (set<int, Compare>::iterator it = s2.begin(); it != s2.end(); it++)
-
- {
-
- cout << *it << " ";
-
- }
-
- cout << endl;
-
- }

当存放自定义数据类型时:
- class Person {
-
- public:
-
- int m_age;
-
- string m_name;
-
- Person(string name, int age)
-
- {
-
- this->m_name = name;
-
- this->m_age = age;
-
- }
-
- };
-
- class PCompare {
-
- public:
-
- bool operator()(const Person &p1,const Person &p2)
-
- {
-
- return p1.m_age > p2.m_age;
-
- }
-
- };
-
-
-
- void printCPerson(set
&s) -
- {
-
- for (set
::iterator it = s.begin(); it != s.end(); it++) -
- {
-
- cout << "姓名:" << it->m_name << " 年龄:" << it->m_age << endl;
-
- }
-
- cout << endl;
-
- }
-
- void test03()
-
- {
-
- //对于自定义的数据类型 必须指定排序规则
-
- set
s2; -
- Person p1("张三", 19);
-
- Person p2("李四", 18);
-
- Person p3("赵云", 29);
-
- Person p4("张飞", 30);
-
- Person p5("刘备", 39);
-
- s2.insert(p1);
-
- s2.insert(p2);
-
- s2.insert(p3);
-
- s2.insert(p4);
-
- s2.insert(p5);
-
- printCPerson(s2); //注意 PCompare类一定要在调用前先定义 不然会报错
-
- }
