先介绍一下pair的用法
pair<T1,T2>类型等价于:
struct {
T1 first;
T2 second;
};
例如 pair<int, double> a;
等价于
struct {
int first;
double second;
}a;
a.first = 1;
a.second = 93.33;
然后来讲一下map和set,会发现,其实这四种都是利用二叉平衡树实现的(AVL),
在算一些数据的时候,如果需要进行大量查找,可以用数组+二分查找进行,但是如果同时需要进行大量的插入,删除,则需要使用到set和map等容器
multiset可以用insert, find, erase来进行logN的查找, 插入, 删除
mutiset<T> st;
st.insert
st.find
st.erase
st.lower_bound(12) <=
st.upper_bound(12) >
自定义排序规则的multiset
multiset<int, greater<int> >st; //跟sort(a,a+n,greater<int>())可以从大到小排序一样
struct Rule1 {
bool operator()(const int& a, const int& b) {
return (a % 10) < (b % 10);
}
};
multiset<int, Rule1 >st;//按照个位数从小到大排
set和multiset的区别是容器里不能有重复的元素
set用法,
pair<set<int>::iterator,bool> result
总结:
multimap里的元素都是pair类型的
按照first排序,
map不能有重复key值,multimap可以有
给一个综合的例题
Description
单词词频统计程序
输入大量单词,每个单词,一行,不超过20字符,没有空 格。 按出现次数从多到少输出这些单词及其出现次数。 出现次数相同的,字典序靠前的在前面
Input
this
is
ok
this
plus
that
is
plus
plus
Output
plus 3
is 2
this 2
ok 1
that 1
#include <iostream>
#include <set>
#include <map>
#include <string>
using namespace std;
/*
map例题:单词词频统计程序
输入大量单词,每个单词,一行,不超过20字符,没有空 格。 按出现次数从多到少输出这些单词及其出现次数。 出现次数相同的,字典序靠前的在前面
INPUT:
this
is
ok
this
plus
that
is
plus
plus
输出样例:
plus 3
is 2
this 2
ok 1
that 1
*/
struct Word {
int times;
string wd;
};
struct Rule { //按照时间从大到小,时间相同则按照名字顺序来
bool operator()(const Word & w1, const Word & w2) {
if (w1.times != w2.times)
return w1.times > w2.times;
else
return w1.wd < w2.wd;
}
};
/*
思路:先对输入的数据进行统计,用map得到每个单词对应的次数
然后用set对单词的次数和字母表顺序进行排序
http://www.icourse163.org/learn/PKU-1001553023?tid=1001762001#/learn/content
*/
int main()
{
string str;
set<Word, Rule> st;
map<string, int>mp;
while (cin >> str)
mp[str]++;
for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++)
{
Word tmp;
tmp.wd = it->first;
tmp.times = it->second;
st.insert(tmp);//插入进行后直接按照自定义的Rule排序
}
for (set<Word, Rule>::iterator it = st.begin(); it != st.end(); it++)
{
cout << it->wd << " " << it->times << endl;
}
return 0;
}