set集合容器,就是一个存放集合的容器,存储时候自动判断是否与已存在元素相同,相同的话自觉跳过。
自定义元素存放方式,比如mycomp函数元素从大到小存放。
struct mycomp{ // 自定义比较函数mycomp
bool operator() (const int &a,const int &b){
return a>b; // "()"重载运算符
}
};
set<int,mycomp> s; 声明变量
主要有下面这些函数:
s.insert(k);
插入元素s.erase(k);
set删除元素s.clear();
set集合容器清空s.size();
set集合容量s.find(k);
元素查找,返回迭代器位置
multiset 多重集合容器:
multiset<string> p;
//multiset 多重集合容器(允许有重复元素的
int k=p.erase("123123");
//multiset删除元素,多个的话全部删除并统计个数
#include <iostream>
#include <vector>
#include <string>
#include <set>
using namespace std;
struct mycomp{ // 自定义比较函数mycomp
bool operator() (const int &a,const int &b){
return a>b; // "()"重载运算符
}
};
struct info{ // set中结构体元素
string name; // "<" 重载运算符
double score;
bool operator< (const info &a) const{
return a.score<score;
}
};
int main()
{
set<int,mycomp> s; // set自定义比较函数mycomp
s.insert(8); // 插入元素
s.insert(12);
s.insert(98);
s.insert(8); // 重复插入元素的时候不会执行
s.insert(75);
set<int>::iterator it; // 迭代器
for(it=s.begin();it!=s.end();it++)
cout<<*it<<" ";
cout<<endl;
set<int>::reverse_iterator rit; // 反向迭代器
for(rit=s.rbegin();rit!=s.rend();rit++)
cout<<*rit<<" ";
cout<<endl;
it=s.find(3); // set集合元素检索
if(it!=s.end())
cout<<*it<<endl;
else
cout<<"not found it!"<<endl;
s.erase(12); // set删除元素
s.clear(); // set集合容器清空
s.size(); // set集合容器的容量
multiset<string> p; //multiset 多重集合容器(允许有重复元素的集合)
p.insert("123123");
p.insert("123123");
p.insert("abc");
p.insert("bcd");
int k=p.erase("123123"); // multiset删除元素,多个的话
全部删除并统计个数
multiset<string>::iterator fp;
for(fp=p.begin();fp!=p.end();fp++)
cout<<*fp<<" ";
cout<<k<<endl;
fp=p.find("abc"); // 元素查找
cout<<*fp<<endl;
return 0;
}