非线性数据结构
set集合
①有序不重复 set ②有序可重复 multiset ③无序不重复 unordered_set
④无序可重复 unordered_multiset
有序省内存 无序省时间
//头文件
#include <set>
#include <unordered_set>
//构造
set<int> set1={1,2,3};//有序不重复
multiset<int> set2={1,2,3,3,3};//有序可重复
unordered_set<int> set3={1,2,3,4};
unordered_multiset<int> set3={1,2,3,4};
//遍历集合
unordered_multiset<int>::iterator it;//新增元素
set1.insert(4);
//删除元素
set1.erase(1);
set2.erase(3);
//find查找元素的位置 找不到返回尾后迭代器
if(set3.find(1)==set3.end()){
}
else{
}
//count获取元素的数量
//set元素不允许修改 可以先删除再插入
map词典
数组下标必须是整数
map里面下标可以是任意类型 通过下标访问元素 下标和元素都可以是任意类型 下标成为键 元素称为值 pair/键值对
map本质上是一个集合
#include <stdio.h>
#include <map>
#include <unordered_map>using namespace std;
int main(){/* //构造mapmap<char,int> map1;//有序 不允许键重复//char 是键的类型 int 是值的类型multimap<char,int> map2;//有序 允许重复unordered_map<char,int> map3;//无序 不允许重复unordered_multimap<char,int> map4;//无序 允许重复pair<char,int> pair1={'w',0};printf("key=%c,value=%d\n",pair1.first,pair1.second);map1.insert(pair1);map1.insert({'w',2});//删除 map只删除一个 multimap 同时删除多个键相等的map1.erase('w');*///遍历mapmap<char,int> map1={{'w',0},{'y',2}};map<char,int>::iterator it;for(it=map1.begin();it!=map1.end();++it){printf("key=%c,value=%d\n",it->first,it->second);}//查找 要区别map和multimapprintf("value=%d\n",map1['w']);//如果不存在 新增一个键值对 值为0if(map1.find('a')==map1.end()){printf("not");} else{printf("yes");}//multimap 不支持[]运算符 lower_bound(key)返回key对应的第一个值位置//upper_bound(key) 返回key对应的最后一个值的后一个位置}