1: set(multiset)容器基本用法:
#include <bits/stdc++.h>
#include <set> //set自动排序,不可重复插入;但multiset可重复插入
using namespace std;
typedef long long ll;
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0)
//*writer:cjr
// *start on @date: 2021-07-26 16:47
void Print(set<ll> &s)//打印遍历
{
for (set<ll>::iterator p = s.begin(); p != s.end(); p++)
{
cout << *p << " ";
}
cout << endl;
}
int main()
{
IOS;
set<ll> s, s1, s2;
s.insert(20); //插入
s.insert(10);
s.insert(30);
s.insert(12);
s.insert(12);
Print(s); //打印
pair<set<ll>::iterator, bool> r = s.insert(12);//bool 检测是否插入成功
if (r.second)
cout << "第三次插入成功!" << endl;
else
cout << "第三次插入失败!" << endl;
multiset<ll> ms; //可重复插入
ms.insert(12);
ms.insert(12);
ms.insert(12);
for (multiset<ll>::iterator t = ms.begin(); t != ms.end(); t++)
cout << *t << " ";
cout << endl;
multiset<ll>::iterator pos1 = ms.find(12);
if (pos1 != ms.end())
cout << *pos1 << " ms已找到" << endl;
else
cout << "ms未找到" << endl;
set<ll>::iterator pos = s.find(22);
if (pos != s.end())
cout << *pos << endl;
else
cout << "未找到" << endl;
ll n = s.count(12); //计数
cout << "n=" << n << endl;
/*
s1.insert(300);
s1.insert(120);
Print(s);
Print(s1);
s1.swap(s);
Print(s);
Print(s1);
s.clear();//清除
s.erase(12);//删除值为12
s.erase(s.begin(),s.end());
*/
system("pause");
return 0;
}
输出结果:
10 12 20 30
第三次插入失败!
12 12 12
12 ms已找到
未找到
n=1
请按任意键继续. . .
2: 对于自定义数据类型 ,set必须指定排序规则才可以插入数据
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0)
//*writer:cjr
// *start on @date: 2021-07-27 20:45
class person
{
public:
person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
class compareperson//定义排序规则
{
public:
bool operator()(const person &p1, const person &p2)
{
return p1.m_age > p2.m_age;//按照年龄从大到小排序
}
};
void test()
{
set<person, compareperson> s;
person p1("小红", 12);
person p2("小明", 11);
person p3("小蓝", 16);
person p4("小青", 14);
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
for (set<person, compareperson>::iterator it = s.begin(); it != s.end(); it++)
{
cout << "姓名: " << it->m_name << "年龄:" << it->m_age << endl;
}
}
int main()
{
IOS;
test();
system("pause");
return 0;
}
输出结果:
姓名: 小蓝年龄:16
姓名: 小青年龄:14
姓名: 小红年龄:12
姓名: 小明年龄:11
请按任意键继续. . .
3:random_shuffle(洗牌算法)
#include <bits/stdc++.h>
#include <vector>
#include <ctime>
#include <algorithm>
using namespace std;
typedef long long ll;
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0)
//*writer:cjr
// *start on @date: 2021-07-29 16:12
void Print(int val)
{
cout << val << " ";
}
void test()
{
srand((unsigned int)time(NULL)); //按照系统时间做随机数种子(即每次运行结果不同)
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
random_shuffle(v.begin(), v.end()); //洗牌算法
for_each(v.begin(), v.end(), Print);//打印输出
}
int main()
{
IOS;
test();
// ll a=rand()%3;
//cout<<a;
system("pause");
return 0;
}
输出结果:
请按任意键继续. . .
5 3 0 1 8 6 2 7 9 4
Process returned 0 (0x0) execution time : 1.386 s
Press any key to continue.