map与multimap的用法

# include <iostream>
# include <map>
# include <string>

using namespace std;
/* map(映射)-->键不允许重读 multimap(多映射) -->键允许重复 红黑树 自动依靠key排序 基本操作 insert count find eraser 不能通过find进行修改 */
int main(){

    map<int,string> a;
    multimap<int,string> ma;

    //插入数据方法1. 
    //map<template T,template T> value_type是map的内置类型
    a.insert(map<int,string>::value_type(1,"One"));
    a.insert(map<int,string>::value_type(2,"Two"));
    a.insert(map<int,string>::value_type(3,"Three")); 

    //插入数据方法2.
    // make_pair方法把数据变成一对一对的 
    a.insert(make_pair(-1,"Minus One"));

    //插入数据方法3.
    a.insert(pair<int,string>(1000,"One Thousand"));

    // 插入数据方法4. key --1000 value--One Million
    //这种方法只适合map,不适合multimap,其他三种都可以 
    a[10001]= "One Million";

    //元素的个数
    cout<<a.size()<<endl<<endl; 

    //遍历
    map<int,string>::const_iterator i;
    for(i=a.begin();i!=a.end();i++){
        cout<<"key: "<<i->first<<" ";
        cout<<"value:"<<i->second.c_str();//i->second-->string i->second.c_tr()-->c语言的字符串 
        cout<<endl;
    } 



    ma.insert(multimap<int,string>::value_type(3, "Three")); 
    ma.insert(multimap<int,string>::value_type(45,"Forty Five"));
    ma.insert(make_pair(-1,"Minus One"));
    ma.insert(pair<int,string>(1000,"One Thousand")); 
    ma.insert(pair<int,string>(1000,"One Thousand")); 

    //个数
    cout<<ma.size()<<endl<<endl;//5

    multimap<int,string>::const_iterator im;
    for(im=ma.begin();im!=ma.end();im++){
        cout<<"key: "<<im->first<<" ";
        cout<<"value:"<<im->second.c_str();
        cout<<endl;
    } 

    cout<<"map中有几个1000-->"<<a.count(1000)<<endl;
    cout<<"multumap中几个1000-->"<<ma.count(1000)<<endl; 

    //multimap查找
    multimap<int,string>::const_iterator fi;
    fi = ma.find(45);
    if(fi!=ma.end()){
        //cout<<ma[fi->first]<<endl;error
        cout<<"key: "<<fi->first<<" ";
        cout<<"value:"<<fi->second.c_str();
        cout<<endl;
    }
    cout<<endl;

    //重复的查找 
    fi = ma.find(1000);
    if(fi != ma.end()){
        size_t n = ma.count(1000);
        for(size_t i=0;i<n;i++){
            cout<<"key: "<<fi->first<<" ";
            cout<<"value:"<<fi->second.c_str()<<endl;
            fi++;
        }
    } 
    cout<<endl<<endl;

    //map查找 通过key去找value 
    cout<<a[3]<<endl; 


    map<string,int> score;
    score.insert(make_pair("zhangsan",99));
    score.insert(make_pair("lisi",98));
    score.insert(make_pair("wangwu",88));
    score["xiaoming"] = 100;

    cout<<"wangwu分数:"<<score["wangwu"]<<endl<<endl; 


    //ma中的key为-1删除
    //删除成功返回值>0 
     if(ma.erase(-1)>0){
        cout<<"删除成功!"<<endl<<endl; 
     } 

     //删除方法2
     multimap<int,string>::iterator if2=ma.find(45);
     if(if2!=ma.end()){
        ma.erase(if2);
        cout<<"删除成功!"<<endl<<endl; 
     }

     //删除方法2
     //lower_bound上边界 upper_bound下边界 
     ma.erase(ma.lower_bound(1000),ma.upper_bound(1000));

    return 0;
}

你可能感兴趣的:(map)