首页 > 代码库 > c++ map

c++ map

map 容器存储键值对,提供了很好的一对一的关系。

在内部,元素总按特定的规则有序,通常用二叉搜索树实现。

下面是使用示例:

#include <cstdio>
#include <algorithm>
#include <set>
#include <map>
#include <iostream>
using namespace std;
int main () {
    map<char,int> mymap;

    //first insert method
    mymap.insert(pair<char,int>(a,100));
    mymap.insert(pair<char,int>(z,200));

    //insert函数的返回值类型4
    pair<map<char,int>::iterator,bool> ret;
    ret=mymap.insert(pair<char,int>(z,500));
    if(ret.second==false)
    {
        cout<<"element ‘z‘ already existed"<<endl;
        cout<<"with a value of "<<ret.first->second<<endl;
    }

    //second insert method
    map<char,int>::iterator it=mymap.begin();
    mymap.insert(it,pair<char,int>(b,300));
    mymap.insert(it,pair<char,int>(c,400));

    //third insert method
    map<char,int> anothermap;
    anothermap.insert(mymap.begin(),mymap.find(c));

    cout<<"mymap contains:"<<endl;
    for(it=mymap.begin();it!=mymap.end();it++)
        cout<<it->first<<" => "<<it->second<<endl;

    cout<<"anothermap contains:"<<endl;
    for(it=anothermap.begin();it!=anothermap.end();it++)
        cout<<it->first<<" => "<<it->second<<endl;

    map<char,int> m;
    map<char,int>::iterator itlow,itup;
    m[a]=20;
    m[b]=40;
    m[c]=60;
    m[d]=80;
    m[e]=100;

    itlow=m.lower_bound(b);
    itup=m.upper_bound(d);
    cout<<itlow->second<<" "<<itup->second<<endl;

    m.erase(itlow,itup);
    cout<<"m contains:"<<endl;
    for(it=m.begin();it!=m.end();it++)
        cout<<it->first<<" => "<<it->second<<endl;
}

mapmultimap差别仅仅在于其中的 ‘multiple‘——允许一个键对应多个值。

多维map

技术分享

技术分享

 好像之前发过这题技术分享

技术分享

技术分享

技术分享
#include <cstdio>
#include <algorithm>
#include <set>
#include <map>
#include <iostream>
#include <string>

using namespace std;
map<string,string> m;
int main ()
{
    string t;
    cin>>t;
    string k,v;
    while(true)
    {
        cin>>v;
        if(v=="END") break;
        cin>>k;
        m[k]=v;
    }
    cin>>t;
    string text;
    getline(cin,text);
    while(1)
    {
        getline(cin,text);
        if(text=="END") break;
        int i=0;
        while(i<text.length())
        {
            string word="";
            while(text[i]>=65&&text[i]<=90||text[i]>=97&&text[i]<=122)
            {
                word+=text[i];
                i++;
            }
            if(!(text[i]>=65&&text[i]<=90||text[i]>=97&&text[i]<=122))
            {
                i++;
            }
            if(m.count(word))
            {
                string new_word=m[word];
                int sub=new_word.length()-word.length();
                i+=sub;
                text.replace(text.find(word),word.length(),new_word);
            }
        }
        cout<<text<<endl;
    }
    return 0;
}
View Code

 

c++ map