map的使用

STLmap

mapSTL的一个关联容器,它提供一对一的数据处理能力(其中第一个可以成为关键字,每个关键字只能出现一次,第二个值对应该关键字的值)

Map内部自建一颗红黑树,这棵树具有对数自动排序的功能,所以在map内部所有的数据都是有序的

 

map的特点是增加和删除节点对得带起的影响很小,处理那个擦操作节点,对其他节点没有影响。

对于迭代器来说,可以修改值value,不能修改键key

 

mapkey-value的对应,可以根据key值快速查找记录,查找的复杂度基本log(N),可以快速插入,删除,根据key修改value,可以便利所有记录

map的使用

1:在map中元素有两种插入方法:(map中插入会自动排序)

·使用下标

·使用insert函数

map<int,int> mp;

for(int i=0;i<10;i++){

    mp[i]=i;////存入的是ii,默认mp中的每一对都是第一个数是i,第二个数也是i

}

for(int i=10;i<20;i++){

    mp.insert(make_pair(i,i));/////同上,也是第一个数与第二个数相同

}


2:对数据遍历

·正序迭代器

·反向迭代器

·数组

map<int,int>::iterator it;/////使用迭代器,正序

for(it=mp.begin();it!=mp.end();it++){

   cout<<it->first<<","<<it->second<<endl;

}

map<int, string>::reverse_iterator  iter;///用反相迭代器

  for(iter = mp.rbegin(); iter != mp.rend(); iter++){

   cout<<iter->first<<"   "<<iter->second<<endl;

}

for(int nIndex = 1; nIndex <=mapStudent.size()  ; nIndex++) {////数组

           cout<<mapStudent[nIndex]<<endl;

}

 

3:查找

·count判定关键字是否出现返回1是存在,返回0是不存在

·find,查找数据的位置,如果存在就返回位置,没有存在则返回的迭代器等于end函数返回的迭代器

int c=mapStudent.count(1);

       cout<<c;

iter = mapStudent.find(1);///find传入的只能是键值,即第一个数(按键查询)

if(iter != mapStudent.end()){

     cout<<"Find, the value is "<<iter->second<<endl;

}

 

4:清空和判断

·clear() and empty()

 

5:数据的删除

·erase函数,有三种方式

///使用关键字删除,删除了就会返回1 ,否则返回0

int n=mapStudent.erase(1);

///使用迭代器删除,先找到关键字返回迭代器,通过迭代器删除

        map<int,string>::iterator it;

        it=mapStudent.find(1);

        mapStudent.erase(it);

//用迭代器,成片的删除  //一下代码把整个map清空  

mapStudent.earse(mapStudent.begin(), mapStudent.end());

 

6:排序

STL中默认是采用小于号来排序的,关键字是int或其他可以支持排序的就没有问题,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题

 

class student{

    public:

    student(int id=0,int age=0):ID(id),AGE(age){}

    int ID;

    int AGE;

};

///根据年龄大到小排序

class comp{

public:

    bool operator()(const student& stu1,const student& stu2)const{

        return stu1.AGE>stu2.AGE;

    }

};

 

int main(){

    map<student,int,comp> mapStudent;

    student stu;

    int num=90,j=9;

    for(int i=5;i>1;i--){

      stu.ID = i;

      stu.AGE = j++;

       mapStudent.insert(pair<student, int>(stu, num));

       num--;

     }

      map<student, int>::iterator iter;

      for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)

      {cout<<iter->first.ID<<":"<<iter->first.AGE<<"::"<<iter->second<<endl;}

return 0;

}

 

 

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/qq_39667655/article/details/80194767