map是一种关联容器,它提供一对一的数据处理能力。map实现从键(key)到值(value)的映射。map效率高的原因是它用平衡二叉搜索树来存储和访问。头文件为map。
- 例如有一个常见的问题,有n个学生,每个人有姓名和学号,现在给定有个学生的name,要求查他的id。
简单的做法可以定义string name[n]和int id[n],或者放在同一个结构体中储存信息,然后在name[]中查找学生,找到后使用下标输出他的id。这样做虽然可行但是需要搜索所有的name[],复杂度为O(n),效率很低。
利用STL中的map容器可以快速实现这个查找,复杂度为O(log2n)。map中的元素都会自动根据键值进行排序。
在本例子中map的具体操作如下:
定义:map<string,int> StudentInfo; //定义学生信息容器,储存name和id
赋值:StudentInfo["Tom"] = 15; //可以直接以string当下标使用
查找:在用姓名查找学号时可以直接用StudentInfo["Tom"]来使用,其值便为学号。
map的具体操作
map<type,type> stu; //map的定义,需要有两种类型
stu.insert(map<type,type>::value_type(n,m); //将n和m对应类型的变量插入到map里
stu.insert(pair<type,type>(n,m)); //使用pair来将变量插入到map里
stu[n] = m; //直接赋值
stu.begin();
stu.end(); //和vector中的用法一样
stu.clear();//清空容器
it->first //指第一个元素
it->second //指第二个元素
- map中的查找需要使用迭代器iterator和find函数(包括指定删除也需要迭代器)
map<int, string> StudentInfo;//定义map
map<int, string>::iterator it;//定义迭代器
//中间赋值的就略过
it = StudentInfo.find(5);//查找
StudentInfo.erase(it);//删除
用法示例
- Shopping
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2118 Accepted Submission(s): 706
Problem Description
Every girl likes shopping,so does dandelion.Now she finds the shop is increasing the price every day because the Spring Festival is coming .She is fond of a shop which is called “memory”. Now she wants to know the rank of this shop’s price after the change of everyday.
Input
One line contians a number n ( n<=10000),stands for the number of shops.
Then n lines ,each line contains a string (the length is short than 31 and only contains lowercase letters and capital letters.)stands for the name of the shop.
Then a line contians a number m (1<=m<=50),stands for the days .
Then m parts , every parts contians n lines , each line contians a number s and a string p ,stands for this day ,the shop p 's price has increased s.
Output
Contains m lines ,In the ith line print a number of the shop “memory” ‘s rank after the ith day. We define the rank as :If there are t shops’ price is higher than the “memory” , than its rank is t+1.
Sample Input
3 memory kfc wind 2 49 memory 49 kfc 48 wind 80 kfc 85 wind 83 memory
Sample Output
1 2
Author
dandelion
#include<map>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int n, m, p;
string s;//店名
map<string, int> shop;
while (cin >> n)
{
shop.clear();
for (int i = 0;i < n;i++)//输入店名
cin >> s;
cin >> m;
while (m--)
for (int i = 0; i < n; i++)
{
cin >> p >> s;
shop[s] += p;//直接使用map进行赋值
}
int rank = 1;//排名
for (auto it = shop.begin(); it != shop.end(); it++)
if (it->second > shop["memory"])//比较价位
rank++;
cout << rank << endl;
}
return 0;
}