头文件还是 set
用法和set一样,所有set改成multiset
multiset 特性及用法和 set 完全相同,唯一的差别在于它允许键值重复。
1 内置数据类型
#include<iostream>
#include<set>
#include<map>
using namespace std;
//仿函数:重载函数调用运算符()的类;;;定义排序规则
class Mycompare {
public:
bool operator()(int v1, int v2)const {//重载运算符
return v1 < v2;//降序排列
}
};
void printSetInt(multiset<int, Mycompare>& s) {
multiset<int, Mycompare>::iterator it = s.begin();
for (; it != s.end(); it++)
cout << *it << " ";
cout << endl;
}
void test1() {
//multiset<int> s;//默认升序
multiset<int, Mycompare> s;//multiset<int,排序规则> s; //默认升序,这里可以修改排序规则,仿函数实现
s.insert(30);
s.insert(30);
s.insert(50);
s.insert(90);
s.insert(70);
//打印
cout << "大小:" << s.size() << endl;
printSetInt(s);
//对组
pair<multiset<int>::iterator, multiset<int>::iterator> pa;
pa = s.equal_range(50);//同时返回,上下限两个迭代器,用对组接收返回值
if (pa.first != s.end())
cout << "\n下限lower_bound(50)为:" << *(pa.first) << endl;
if (pa.second != s.end())
cout << "上限upper_bound(50)为:" << *(pa.second) << endl;
}
2 自定义数据类型
//自定义数据类型
class Person {
public:
Person(string name, int age) {
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
//按照年龄排序
class Mycompare2 {//因为要访问,Person 的私有变量m_Name、m_Age,将Mycompare2类设为有元
public:
bool operator()(Person p1, Person p2) const {
return p1.m_Age < p2.m_Age;
}
};
void printSetPerson(multiset<Person, Mycompare2>& s) {
multiset<Person, Mycompare2>::iterator it = s.begin();
for (; it != s.end(); it++)
cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << endl;
cout << endl;
}
//multiset 允许两个元素有相同的键值。
//姓名不同,年龄相同;年龄相同,年龄不同;;;看看结果那些会被去重
Person p1(“赵”, 26), p2(“孙”, 26), p3(“孙”, 22);
void test2() {
multiset<Person, Mycompare2> s;
s.insert(Person("张", 60));
s.insert(Person("刘", 25));
//multiset 允许两个元素有相同的键值。
//姓名不同,年龄相同;年龄相同,年龄不同;;;看看结果那些会被去重
Person p1("赵", 26), p2("孙", 26), p3("孙", 22);
s.insert(p1);
s.insert(p2);
s.insert(p3);
//打印
cout << "大小:" << s.size() << endl;
printSetPerson(s);
if (s.find(p3) != s.end())
cout << p3.m_Name << " " << p3.m_Age << endl;
}
int main() {
test2();
return 0;
}
全部保留
3 队组 pair
//对组
void test3() {
//方式1:
pair<int, string> p1(10086,"移动");
pair<string, int> p2("电信",10001);
pair<int, string> p3(10010,"联通");
//方式2:(推荐)
pair<int, string> p4 = make_pair(9557,"建行");
//访问
cout << p1.first << " " << p1.second << endl;
cout << p2.first << " " << p2.second << endl;
cout << p3.first << " " << p3.second << endl;
cout << p4.first << " " << p4.second << endl;
}