map是STL中映射. 使用起来还是很方便的.
支持自定义排序规则(对key)
支持多维映射
常用操作
#include < map>
map< string, int> dict;
map< string, map< int, string> >dict;
count()函数
erase()函数
empty()函数
insert()函数
map< string, int>::iterator it = dict.begin();
it->first; //key
it->second; //value
dict[1] = 3232; //直接建立映射, 无论是否存在
map<string, int, cmp> dict;
struct cmp {
bool operator (string x, string y) {
return x < y;
}
};
自定义排序规则和set非常像, 几乎一样
#include <iostream>
#include <map>
using namespace std;
struct cmp {
bool operator () (int x, int y) {
return x > y;
}
};
int main()
{
map<int, int, cmp> dict;
map<int, int> dic;
for(int i = 0; i < 10; ++i) {
dict.insert(pair<int, int>(10 - i, 10 - i));
dic.insert(pair<int, int>(10 - i, 10 - i));
}
for(map<int, int>::iterator it = dict.begin(); it != dict.end(); ++it) {
cout << it->first << ' ' << it->second << endl;
}
cout << endl << endl;
for(map<int, int>::iterator is = dic.begin(); is != dic.end(); ++is) {
cout << is->first << ' ' << is->second << endl;
}
}
.
蒜头君面试
这道题老师的优化可以说非常精彩了, 以后要自己写出这样的优化.
蒜头君来蒜厂面试的时候,曾经遇到这样一个面试题:
给定 nn 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给蒜头君难住了。现在蒜头君来考考你。
输入格式
第一行输入一个整数 n(1 \le n \le 100000)n(1≤n≤100000),接下来一行输入 nn 个 int 范围内的整数。
输出格式
输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。
样例输入1
5
1 1 2 3 4
样例输出1
1 2
样例输入2
10
9 10 27 4 9 10 3 1 2 6
样例输出2
10 2
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n, x, max = -0x7fffffff, maxx = -1;
cin >> n;
map<int, int> dict;
while(n--) {
cin >> x;
dict[x]++;
if(dict[x] > max || (dict[x] == max && x > maxx)) {
max = dict[maxx = x];
}
}
cout << maxx << ' ' << max;
}
.
水果店
二维map的应用
蒜头君经营着一个不大的水果店。他认为生存之道就是经营最受顾客欢迎的水果。现在他想要一份水果销售情况的明细表,这样就可以很容易掌握所有水果的销售情况了。蒜头君告诉你每一笔销售记录的水果名称,产地和销售的数量,请你帮他生成明细表。
输入格式
第一行是一个整数 N(0 < N \le 1000)N(0<N≤1000),表示蒜头君有 NN 次成功的交易。其后有 NN 行数据,每行表示一次交易,由水果名称(小写字母组成,长度不超过 100100),水果产地(小写字母组成,长度不超过 100100)和交易的水果数目(正整数,不超过 10001000)组成.
输出格式
请你输出一份排版格式正确(请分析样本输出)的水果销售情况明细表。这份明细表包括所有水果的产地、名称和销售数目的信息。水果先按产地分类,产地按字母顺序排列;同一产地的水果按照名称排序,名称按字母顺序排序。
样例输入
5
apple shandong 3
pineapple guangdong 1
sugarcane guangdong 1
pineapple guangdong 3
pineapple guangdong 1
样例输出
guangdong
|----pineapple(5)
|----sugarcane(1)
shandong
|----apple(3)
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, map<string, int> > dict;
string a, b;
int c;
int n;
cin >> n;
for(int i = 0; i < n; ++i) {
cin >> a >> b >> c;
if(dict.count(b) && dict[b].count(a)) {
dict[b][a] += c;
} else {
dict[b][a] = c;
}
}
for(map<string, map<string, int> >::iterator it = dict.begin(); it != dict.end(); ++it) {
cout << it->first << endl;
for(map<string, int>::iterator is = it->second.begin(); is != it->second.end(); ++is) {
cout << " |----" << is->first << '(' << is->second << ')' << endl;
}
}
}