STL之map

来源:互联网 发布:sql数据库卸载 编辑:程序博客网 时间:2024/05/29 10:56

下面的代码实现map的删除,添加,清空的基本操作; 对于map的find方法很多新手比较困惑,若果找不到迭代器返回值是什么?

答案是会返回end()。


    #include <map>      #include <string>      #include <iostream>      using namespace std;      int _tmain(int argc, _TCHAR* argv[])      {                           map<int, string> mapStudent;                    mapStudent.insert(pair<int, string>(10001,"bojie")); //添加                    mapStudent.insert(pair<int, string>(10002,"小明"));                    mapStudent.insert(pair<int, string>(10004,"小雪"));                    mapStudent.insert(pair<int, string>(10005,"小小"));                            mapStudent.insert(pair<int, string>(10003,"小白"));//map默认会自动按第一个key从小到大排序。                    map<int, string>::iterator  iter;                    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)                    {                  cout<<iter->first<<"  "<<iter->second<<endl;                                }                      cout<<endl;                    mapStudent.erase(10001); //删除<p>            //  其中如果要删除还有一种常用的方法,用迭代器删除 ,如下</p><p>            //   map<int, string>::iterator iter;</p><p>            //   iter = mapStudent.find(1);</p><p>            //    mapStudent.erase(iter);              for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)              {                  cout<<iter->first<<"  "<<iter->second<<endl;              }                    mapStudent.clear();    //清空              for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)              {                  cout<<iter->first<<"  "<<iter->second<<endl;              }                       while(1);             return 0;      }  

map的基本操作函数:
      C++ Maps是一种关联式容器,包含“关键字/值”对
      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的函数

0 0