算法入门-STL入门学习set
set 通常用于去重,即里面存在的元素各不相同。
可以和结构体相结合使用,但需要重载运算符。
//自定义排序规则
bool operator<(const stu &tmp) const {
if (this->num < tmp.num)
return true;
return false;
}
完整代码
//
// Created by 29273 on 2021-03-22.
//
#include "bits/stdc++.h"
using namespace std;
struct stu {
int num;
string str;
stu(int num, string str) {
this->num = num;
this->str = str;
}
//自定义排序规则
bool operator<(const stu &tmp) const {
if (this->num < tmp.num)
return true;
return false;
}
};
int main() {
set<stu> s1;
// 查看set是否为空
cout << s1.empty() << endl;
s1.insert(stu(1, "2"));
s1.insert(stu(2, "2"));
s1.insert(stu(3, "2"));
cout << s1.size() << endl;
s1.insert(stu(1, "2"));
cout << s1.size() << endl;
s1.insert(stu(1, "5"));
cout << s1.size() << endl;
// 判断数据存不存在0为不存在,1不存在
cout << s1.count(stu(1, "2")) << endl;
s1.clear();
cout << s1.size() << endl;
return 0;
}

浙公网安备 33010602011771号