关联容器map

关联容器支持高效的关键字查找和访问。

map:

关联数组:保存关键字key - 值value对。按关键字有序保存。内部是红黑树结构。
对于迭代器来说,可以修改value,而不能修改key

map数据插入:

#include <iostream>  
#include <map>  
#include <string>  
using namespace std;  
  
int main()  
{  
    map<int, string> mapStudent;  

    //直接用下标方式插入数据
    mapStudent[1] = "student_one";

    //用insert函数插入pair数据
    mapStudent.insert(pair<int, string>(2, "student_two"));  

    //用insert函数插入value_type数据
    mapStudent.insert(map<int, string>::value_type (3, "student_three"));
  
    map<int, string>::iterator iter;  
  
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
        cout<<iter->first<<' '<<iter->second<<endl;  
    }

    return 0;
} 

注意:当map中已有某个关键字时,再使用insert是无法插入数据的,但用下标方式就可以覆盖该关键字之前的值。

map的遍历:

猜你喜欢

转载自www.cnblogs.com/chongjz/p/12796518.html