`
tjmzgn
  • 浏览: 155884 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

C++ MAP 基本用法

    博客分类:
  • C++
阅读更多
/*
    map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,
    所以在map内部所有的数据都是有序的。

*/
#include <iostream>
#include <map>
using namespace std;
typedef map<int,string> mapStudent;
typedef map<int,string>::iterator mapStudengIter;
typedef pair<int,string> Param;

int main()
{
    cout<<"========================"<<endl;
    mapStudent mapstudent;
    mapStudengIter iter,finditer;
    mapstudent[4]  = "student_four";
    mapstudent.insert(Param(1,"Tongjm"));
    mapstudent.insert(Param(2,"Zhaoxp"));
    mapstudent.insert(map<int, string>::value_type (3,"student_three"));
    mapstudent[10] = "student_ten";
    mapstudent[10] = "student_ele";
    /*
    以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,
    用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,
    insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值,用程序说明
    */
    for(iter = mapstudent.begin();iter!=mapstudent.end();iter++ )
    {
        cout<< iter->first<<"--->"<<iter->second<<endl;                 
    }
    cout<<mapstudent.size()<<endl;
    cout<<mapstudent[10]<<endl;
    /*
    用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,
    如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明
    */
    finditer = mapstudent.find(2);
    if(finditer!=mapstudent.end())
    {
        cout<< finditer->first<<"--->"<<finditer->second<<endl;                             
    }
    /*
     数据的清空与判空
     清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map
    */
    if((!mapstudent.empty())== true)
    cout<<"非空"<<endl;
    int n = mapstudent.erase(9);
    for(iter = mapstudent.begin();iter!=mapstudent.end();iter++ )
    {
        cout<< iter->first<<"--->"<<iter->second<<endl;                 
    }
    //功能等同于 mapstudent.clear()
    mapstudent.erase(mapstudent.begin(),mapstudent.end());
    //mapstudent.clear();
    if(mapstudent.empty()== true)
    cout<<"空"<<endl;
   
    system("pause");   
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics