原文地址

map的特性是,所有元素都会根据元素的键值自动被排序。map的所有元素都是pair,同时拥有实值(value)和键值(key)。pair的第一个元素会被视为键值,第二个元素会被视为实值。map不允许两个元素拥有相同的键值。

 

一、map的基本操作函数:  

begin()          返回指向map头部的迭代器
clear()          删除所有元素
count()          返回指定元素出现的次数
empty()          如果map为空则返回true
end()            返回指向map末尾的迭代器
equal_range()    返回特殊条目的迭代器对
erase()          删除一个元素
find()           查找一个元素
get_allocator()  返回map的配置器
insert()         插入元素
key_comp()       返回比较元素key的函数
lower_bound()    返回键值>=给定元素的第一个位置
max_size()       返回可以容纳的最大元素个数
rbegin()         返回一个指向map尾部的逆向迭代器
rend()           返回一个指向map头部的逆向迭代器
size()           返回map中元素的个数
swap()           交换两个map
upper_bound()    返回键值>给定元素的第一个位置
value_comp()     返回比较元素value的函数

二、map的基本构造函数

map<string , int >strMap;        

map<int ,string >intMap;

map<sring, char>strMap;        

map< char ,string>charMap;

map<char ,int>charMap;           

map<int ,char >intMap;

三、map添加数据

 map<int ,string> maplive;  
1.pair<int,string> value(1,"a");maplive.insert(value);    //等价于maplive.insert(pair<int,string>(1,"a"));

2. maplive.insert(map<int,string>::value_type(1,"a"));

3. maplive[1]="a";                                                             //map中最简单最常用的插入添加!

 

#include <iostream>
#include "string.h"
#include "stdio.h"
#include<map>
using namespace std;

int main(){
    map<string,int> strMap;  //以string为键值,以int为实值
    strMap[string("jjhou")] = 1;
    strMap[string("jerry")] = 2;
    strMap[string("jason")] = 3;
    strMap[string("jimmy")] = 4;

    pair<string,int> value(string("david"),5);
    strMap.insert(value);//插入新元素

    map<string,int>::iterator strmap_iter = strMap.begin();
    for(;strmap_iter !=strMap.end();strmap_iter++)
    {
        cout<<strmap_iter->first<<' '<<strmap_iter->second<<endl;
    }
    cout<<endl;

    int number = strMap[string("jjhou")];
    cout<<number<<endl;
    cout<<endl;

    //查找元素
    map<string,int>::iterator iter1;
    //面对关联式容器,应该使用其所提供的find函数来搜索元素,会比使用STL算法find()更有效率。因为STL算法find()只是循环搜索。
    iter1 = strMap.find(string("mchen"));
    if(iter1 == strMap.end())
        cout<<"mchen no fount"<<endl;
        cout<<endl;

    iter1 = strMap.find(string("jerry"));
    if(iter1 != strMap.end())
        cout<<"jerry fount"<<endl;
        cout<<endl;

    //修改实值,键值不可修改
    iter1->second = 9; //可以通过map迭代器修改“value”(not key)
    int number1 = strMap[string("jerry")];
    cout<<number1<<endl;
    
    //删除元素
    map<string,int>::iterator strmap_iter1 = strMap.begin();
    for(;strmap_iter1 !=strMap.end();strmap_iter1++)
    {
        cout<<strmap_iter1->first<<' '<<strmap_iter1->second<<endl;
    }
    cout<<endl;
    
    strMap.erase(iter1);//删除一个条目
    strMap.erase(string("jason"));//根据键值删除

    map<string,int>::iterator strmap_iter2 = strMap.begin();
    for(;strmap_iter2 !=strMap.end();strmap_iter2++)
    {
        cout<<strmap_iter2->first<<' '<<strmap_iter2->second<<endl;
    }
}