1.定義
set,就是數學上的集合——即set中的每一個元素只能出現一次,並且set中的元素是已經從小到大排好序的,使用set需要引入頭文件#include<set>
2.基本函數
2.1構造函數
- std::set<int> se:創建一個空的set
- std::set<int> se{1,2,3,4,5}:創建一個擁有元素1,2,3,4,5的set
- std::set<int> se1(se):創建一個和se相同的set
- std::set<int> se2(se1.begin(),se1.end()):創建一個擁有[se1.begin(),se1.end()]之間元素的set
2.2.添加元素
- se.insert(4):添加一個元素4
- se.insert(pos,7):在pos處添加元素7,但是最後se中的元素會重新排好序
2.3.刪除元素
- se.erase(5):刪除一個元素5
- se.erase(se.begin(),++se.begin()):刪除[begin(),++begin()]之間的元素
- se.clear():清空set中的所有元素
2.4.set重要的迭代器
- se.begin():返回正向迭代器的第一個元素
- se.end():返回正向迭代器的最後一個元素的下一個位置
- se.rbegin():返回反向迭代器的第一個元素,即vector中的最後一個元素
- se.rend():返回反向迭代器的最後一個元素的下一個位置,即vector中的第一個元素的前一個位置
2.5.其他函數
- se.size():set的大小
- se.empty():判斷se的大小
- se.count(key):查找鍵key的元素個數
- se.find(key):如果存在key,返回key所對應的迭代器,否則返回se.end()
- se.upper_bound(key):返回第一個元素大於key的迭代器
- se.lower_bound(key):返回最後一個元素小於key的迭代器
- swap():交換兩個set
- se.emplace()
3.使用實例
3.1.排序
對set的運算符重載使得其可以對非標準類型進行排序
#include<iostream>
#include<set>
#include<string>
struct Infomation
{
std::string name;
int score;
bool operator < (const Infomation &a) const
{
return a.score > score;
}
};
void main(){
std::set<Infomation> se;
Infomation info;
info.name = "haha";
info.score = 30;
se.insert(info);
info.name = "hahaha";
info.score = 40;
se.insert(info);
info.name = "hahahaha";
info.score = 60;
se.insert(info);
for (auto ll : se)
{
std::cout << ll.name << " ";
}
std::cout << std::endl;
}
或者選擇重載()
#include<iostream>
#include<set>
#include<string>
struct Infomation
{
std::string name;
int score;
};
typedef struct{
bool operator()(const Infomation lhs, const Infomation rhs){
return lhs.score < rhs.score;
}
}compare;
void main(){
std::set<Infomation,compare> se;
Infomation info;
info.name = "haha";
info.score = 30;
se.insert(info);
info.name = "hahaha";
info.score = 40;
se.insert(info);
info.name = "hahahaha";
info.score = 60;
se.insert(info);
for (auto ll : se)
{
std::cout << ll.name << " ";
}
}
3.2.添加一個非標準元素
我們除了可以使用insert添加非標準元素,還可以使用emplace和emplace_hint快速添加元素,不同的是兩者返回值不同,emplace返回一個迭代器和是否加入成功的pair,而emplace_hint只是返回迭代器。且emplace_hint比emplace多需要一個迭代器參數
#include<iostream>
#include<set>
#include<string>
struct Infomation
{
std::string name;
int score;
Infomation(std::string _name, int _score) : name(_name), score(_score){}
};
typedef struct{
bool operator()(const Infomation lhs, const Infomation rhs){
return lhs.score < rhs.score;
}
}compare;
void main(){
std::set<Infomation,compare> se;
se.insert(Infomation("haha",30));
se.insert(Infomation("hahaha", 40));
se.insert(Infomation("hahahaha", 60));
se.emplace("az", 10);
auto iter=se.emplace_hint(se.begin(),"xx", 20);
for (auto ll : se)
{
std::cout << ll.name << " ";
}
}