map容器

代码:

#include<iostream>
#include<map>

using namespace std;


int main()
{

    map<string,int>m;//-----------map<key,T>

    m["aaa"]=111;
    m["bbb"]=222;
    m["ccc"]=333;

    map<string,int>::iterator it;//---------------------添加迭代器
    for(it=m.begin();it!=m.end();it++)//-------------------遍历
        cout<<it->first<<"-----"<<it->second<<endl;
cout<<"1============================================================================"<<endl;

    m["aa"]=111;//添加一个元素。
    m["aaa"]=112;//添加一个key相同的元素。

    for(it=m.begin();it!=m.end();it++)//-------------------遍历
        cout<<it->first<<"-----"<<it->second<<endl;

cout<<"2============================================================================"<<endl;

    it=m.begin();m.erase(it);
    m.erase("aaa");
    //m.erase(222);// --------------error!!

    for(it=m.begin();it!=m.end();it++)//-------------------遍历
        cout<<it->first<<"-----"<<it->second<<endl;

cout<<"3============================================================================"<<endl;

    it=m.find("bbb");//利用find()进行定位
    m.erase(it);
    for(it=m.begin();it!=m.end();it++)//-------------------遍历
        cout<<it->first<<"-----"<<it->second<<endl;

}


输出结果为:

aaa-----111
bbb-----222
ccc-----333
1============================================================================
aa-----111
aaa-----112
bbb-----222
ccc-----333
2============================================================================
bbb-----222
ccc-----333
3============================================================================
ccc-----333

猜你喜欢

转载自blog.csdn.net/it8343/article/details/80524740
今日推荐