set的个性:
* 元素就是key,没有value,key不允许重复
* 插入重复的key会被丢弃默认使用小于来排序,自定义类型要定义小于号
set用于管理一组不可重复的数据
multiset 的个性
元素就是key允许有重复的key
管理一组可重复的数据
set的示例
#include <set>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include "show.h"
int main()
{
set<string> ss;
string s;
ifstream fin("maillist");
if(!fin)
{
return -1;
}
while(fin >> s)
{
ss.insert(s);
}
show(ss.begin(),ss.end(),'\n');
return 0;
}
multiset的示例
#include <set>
#include <iostream>
#include <string>
#include <fstream>
#include <map>
using namespace std;
#include "show.h"
template<typename K,typename V>
ostream& operator<<(ostream& o,const pair<K,V> &p)
{
return o << p.first << ":" << p.second ;
}
/*
*我尝试让排序以升序
但出了这样的错误
error: ‘bool operator<(int, int)’ must have an argument of class or enumerated type
看来纯内置类型的运算符是不能重写的
bool operator<(const int a,const int b)
{
return !(a<b);
}
*/
int main()
{
multiset<string> ms;
string name;
cout << "请输入你选举的人的姓名:(ctrl+d 结束)" << endl;
while(cin >> name)
{
ms.insert(name);
}
show(ms.begin(),ms.end());
/*
请输入你选举的人的姓名:(ctrl+d 结束)
furong
chunge
furong
chunge
zengge
chunge chunge furong furong zengge //重复的不丢弃 已排好序
*/
/* 按选票排名 */
multimap<int,string,KeyComp> cnt; //选票可能相同
multiset<string>::iterator ib =ms.begin();
int count;
while(ib != ms.end())
{
count = ms.count(*ib);
cnt.insert(make_pair(count,*ib));
ib = ms.upper_bound(*ib);
}
show(cnt.begin(),cnt.end());
return 0;
}