首页 > 其他 > 详细

映射:map专题

时间:2019-02-02 18:40:10      阅读:202      评论:0      收藏:0      [点我收藏+]

 

 

概念:摘自《算法竞赛入门经典》——刘汝佳:map就是从键(key)到值(value)的映射。因为重载了[]运算符,map像是数组的“高级版”。

例如可以用一个map<string, int> month_name 来表示“月份名字到月份编号”的映射然后用month_name["July"] = 7 这样的方式来赋值。

Map中的元素是自动按key升序排序,所以不能对map用sort函数:

map的功能: 

1. 自动建立Key - value的对应。key 和 value可以是任意你需要的类型。
2. 根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。
3. 快速插入Key - Value 记录。
4. 快速删除记录
5. 根据Key 修改value记录。
6. 遍历所有记录。

map多用于查找很方便快捷,尤其是以键和值的形式存在的。在大量数据中使用map,查询效率很高。 

举例:

map<int, string> student;
student.insert(pair<int, string>(54090101, "Mike"));
student.insert(pair<int, string>(54090102, "MIKE"));
student.insert(map<int, string>::value_type(54090103, "Sam"));
student.insert(map<int, string>::value_type(54090104, "SAM"));
student[54090105] = "Jake";
student[54090105] = "JAKE";//键值为标识,重复插入,结果为替换
studentMessage[54090104] = "Bob";
studentMessage[54090105] = "Ben";

遍历
map<int, string>::iterator iter;
for (iter = student.begin(); iter != student.end(); ++iter)
{
cout << iter->first << ": " << iter->second << endl;
}

C++ map的基本操作和使用:

http://blog.sina.com.cn/s/blog_61533c9b0100fa7w.html

例题uva 156

技术分享图片
#include<iostream>
#include<string>
#include<cctype>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;

map<string,int> cnt;
vector<string>words;

//将单词s进行标准化   即全为小数且字符都是排序的 
string repr(const string& s)
{
    string ans=s;
    for(int i=0;i<ans.length();i++)
    {
        ans[i]=tolower(ans[i]);
    }
    sort(ans.begin(),ans.end());
    return ans;
}

int main()
{
    int n=0;
    string s;
    while(cin>>s)
    {
        if(s[0]==#)
        break;
        words.push_back(s);//向vector数据结构中添加元素 
        string r=repr(s);
        //开始map里面没有内容,它的初始化值是:{},即里边有0个键值对 
        if(cnt.count(r)==0)   //检验被查找的r是否存在,存在返回1,否则为0 
        cnt[r]=0;
        cnt[r]++;//记录每个字符串s搜查之后为s1,统计各个s1的键值 
    } 
    vector<string> ans;
    for(int i=0;i<words.size();i++)
    if(cnt[repr(words[i])]==1)//说明重排也无重复字符串 
    ans.push_back(words[i]);//向vector数据结构中添加元素 
    sort(ans.begin(),ans.end());//按顺序排序 
    for(int i=0;i<ans.size();i++)
    cout<<ans[i]<<"\n";
    return 0;
 } 
View Code

映射:map专题

原文:https://www.cnblogs.com/Aiahtwo/p/10348943.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!