set/multiset容器
与序列式容器的操作是很类似的:
#include<iostream>
#include<set>
using namespace std;
void main()
{
int x[]={1,2,3,4,5,6,1,2,5,7,8,9};
set<int> s(x,x+sizeof(x)/sizeof(int));
multiset<int> ms(x,x+sizeof(x)/sizeof(int));
set<int>::iterator it;
for(it=s.begin();it!=s.end();it++)
cout<<*it<<" ";
cout<<endl;
multiset<int>::iterator mit;
for(mit=ms.begin();mit!=ms.end();mit++)
cout<<*mit<<" ";
cout<<endl;
}
1、set/multiset 都实现了排序,set去掉了重复值,multiset 会保存重复值;
2、没用提供随机访问,即不能通过下标对元素进行访问;
3、可以通过begin 和 end 来查看最小值 或 最大值 :*(s.begin()) 和 *(--s.end()),值得注意的是end不是最后一个元素;
自定义排序:
#include<iostream>
#include <functional>
#include<set>
using namespace std;
struct dst
{
float x;
float y;
};
struct cmp
{
bool operator() (dst a,dst b)
{
return a.x*a.x+a.y*a.y < b.x*b.x+b.y*b.y ;
}
};
void main()
{
int x[]={1,2,3,4,5,6,1,2,5,7,8,9};
set<int,greater<int>> s(x,x+sizeof(x)/sizeof(int));
set<int>::iterator it;
for(it=s.begin();it!=s.end();it++)
cout<<*it<<" ";
cout<<endl;
dst y[]={{1,2},{3,4},{1,0}};
set<dst,cmp> t(y,y+sizeof(y)/sizeof(dst)); ;
set<dst,cmp>::iterator it1;
for(it1=t.begin();it1!=t.end();it1++)
cout<<it1->x<<","<<it1->y<<" ";
cout<<endl;
}
1、使用 greater 实现逆序,包含头文件functional;
2、对结构体dst 进行自定义排序,注意:排序需要自定义的结构体,重载() 运算符;
map/multimap容器
#include<iostream>
#include<map>
#include<string>
using namespace std;
void main()
{
map<string,double> map1;
map1["Tom"]=25.8;
map1["Rose"]=15.2;
map1.insert(pair<string,double>("Jack",25.8));
map1.insert(make_pair("Bob",21.8));
map1.insert(make_pair("Tom",12.4));
map<string,double>::iterator it;
for(it=map1.begin();it!=map1.end();it++)
{
cout<<it->first << ", " <<(*it).second<<endl;
}
cout<<"________________________________"<<endl<<endl;
multimap<string,double> map2;
map2.insert(make_pair("Tom",25.8));//map2["Tom"]=25.8;
map2.insert(make_pair("Rose",15.2));//map2["Rose"]=15.2;
map2.insert(pair<string,double>("Jack",25.8));
map2.insert(make_pair("Bob",21.8));
map2.insert(make_pair("Tom",12.4));
map<string,double>::iterator it1;
for(it1=map2.begin();it1!=map2.end();it1++)
{
cout<<it1->first << ", " <<(*it1).second<<endl;
}
}
输出结果:
1、C11后支持序列赋值进行初始化,如:
map<string,double> map1={{"Tom",25.8},{"Rose",15.2},{"Jack",25.8}};
2、map支持直接赋值 : map1["Tom"]=25.8; multimap则不允许;
3、可以利用pair 或者 直接使用make_pair 给 map/multimap 赋值( 用 insert函数);
4、同样 map 只保存唯一的key ,而 multimap 可以存入多个相同 key 的元素;(不是value)
5、map/multimap 默认根据 key 进行排序,字符串使用 字典序 ;
6、可以自定排序,类似set:
map<string,double,greater<string>> map1; //降序排列
也可以定义排序,这里使用class来实现自定排序:
class cmp
{
public:
bool operator() (string a,string b)
{
return a>b;
}
};
map<string,double,cmp > map1; //降序排列
与结构体类型,需要重载操作符(),并且指定为public属性。