基础实验5-2.2 电话聊天狂人(Map的使用+例题)
1. #include < map>
map容器是一个键值对key-value的映射,其内部实现是一棵以key为关键码的红黑树。Map的key和value可以是任意类型,其中key必须定义小于号运算符。
声明
map<key_type, value_type> name; 例如: map<long, long, bool> vis; map<string, int> hash; map<pair<int, int>, vector> test; 综上:map是可以改变数组角标的,也就是根据指定数组角标类型,这样就是可以把比如字符串类型作为数组的角标,这样我们去找指定字符串,通过数组就可以给它一个位置,之后可以存放该字符串对应的信息 size/empty/clear/begin/end均与set类似。
Insert/erase
与set类似,但其参数均是pair<key_type, value_type>。
find
h.find(x) 在变量名为h的map中查找key为x的二元组。
操作符
h[key] 返回key映射的value的引用,时间复杂度为O(logn)。 []操作符是map最吸引人的地方。我们可以很方便地通过h[key]来得到key对应的value,还可以对h[key]进行赋值操作,改变key对应的value。
size/empty/clear/begin/end
均与set类似
***map函数总结
map<string,string>mp; 1.遍历 for(auto k : mp) k.first; k.second (一般遍历的时候用) 2,头部迭代器 mp.begin()//返回指向map头部的迭代器 map<string,int>::iterator it; it = mp.begin(); //此时,it要用 -> it->first;//注意,从这里可以得出,迭代器表示指针 3.尾部迭代器 mp.end()//返回指向map末尾的迭代器 4.清除 mp.clear()//删除所有元素 5.计数 mp.count()//返回指定元素出现的次数,一键一值,所以count也用来查找 6.判空 mp.empty()//如果map为空返回0,否则返回1 7.查找 mp.find()//返回查找元素所在的迭代器,找不到返回mp.end(); 8.二分 mp.lower_bound()//返回键值>=给定元素的第一个位置 mp.upper_bound()//返回键值>给定元素的第一个位置 9,大小 mp.size()//返回map中元素的个数 10.交换 swap()//交换两个map
2. 应用于什么类型题呢?
适用于 很多 其他类型的数据 分别对应相应的数据,这样的话,就可以用map存储
3. 例题
思路:
1. 数字太长了,可以用字符串存储 2. 比较出现的次数,那就用map存储 3. map[x]++ 则就表示 x角标 入map中
#include <iostream> #include <string> #include <map> using namespace std; int main() { int N, tmp = 0, count; string a, b; cin >> N; map<string, int>mp; while (N-- && cin >> a >> b) mp[a]++, mp[b]++; for (auto& it : mp) if (it.second == tmp) count++; else if (it.second > tmp) count = 1, tmp = it.second, a = it.first; cout << a << " " << tmp; if (count > 1) cout << " " << count; return 0; }
#include<iostream> #include<map> #include<string> #include<cstdio> #define ios ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); using namespace std; map<string,int> m; int main() { ios int n; cin>>n; int ans=0; while(n--){ string x; cin>>x; m[x]++; ans=max(ans,m[x]); cin>>x; m[x]++; ans=max(ans,m[x]); } int ret=0; string a; map<string,int>::iterator it; for(it=m.begin();it!=m.end();it++) { if(it->second==ans) { if(ret==0) a=it->first; ret++; } } if(ret>1) cout<<a<<" "<<ans<<" "<<ret; else cout<<a<<" "<<ans; }
map迭代器
map迭代器相当于指针,通过map<string,int>::iterator it; it = map.begin() 可以得到map相对应的指针地址,然后it -> first 和 if-> second得到 角标和相应的数据 还可以用 auto& it = map;这样的话就可以用 it.first 和 it.second
下一篇:
阿良的算法之路(线性筛筛素数)