学习自
https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html
1.map中关键字与存储对象的值是一对一的关系,它实际上是一颗红黑树,所以其中的元素是有序的,并且默认是升序,这个和sort函数 的默认排序是一样的。可以修改存储对象的值,但是不能修改关键字的值。
2.使用关键字搜索,搜素的时间复杂度是 lg(n) 。
3. 如何定义
map <int,string> map1;//定义了一个 关键字为 int 存储对象值为 string的map
4 如何使用
最简单的方法是当做数组使用:
初始化:
map1[0] = "studentone";//只填充存储对象的关键字的值。
map1[1] = "studenttwo";
使用insert()插入pair数据
初始化:
map1.insert(pair( <int, string>(1,"studentone"));//比较难记,尤为注意这个pair数据。
使用pair插入数据时无法修改已有关键字对应的存储对象的值。如果关键字不存在 插入就是成功的,返回值为true,否则为false;
代码如下:
map<int, string> mapStudent;
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(pair<int, string>(1, "student_one"));
if(Insert_Pair.second == true)
cout<<"Insert Successfully"<<endl;
else
cout<<"Insert Failure"<<endl;
Insert_Pair = mapStudent.insert(pair<int, string>(1, "student_two"));
if(Insert_Pair.second == true)
cout<<"Insert Successfully"<<endl;
else
cout<<"Insert Failure"<<endl;
5。遍历:
使用数组法遍历:
//和插入类似,直接输出其存储对象即可。
cout<<map1[0]<<endl;
使用前向迭代器:
map <int,string> iterator it;
for(it = map1.begin();it!= map1.end();it++){
cout<< it->first <<' '<<it -> second <<endl;
}
使用后向迭代器:
map <int , string> iterator it;
for(it = map1.rbegin();it!=map1.rend();it++){
cout<< it->first <<' '<<it -> second <<endl;
}