map
map是STL的一个关联容器,它提供一对一(唯一的键对应一个值)的数据处理能力。任何两个元素没有相同的key值。
map内部建立一棵红黑树,对数据具有自动排序的功能。所以在map内部所有的数据都是有序的。
map具有重要的属性,就是在map对象中插入一个新元素不指向现有元素的迭代器失效。也没有任何迭代器失效。当然,实际上指向只在被上删除的元素的迭代器。
定义map
map<int,string> mapStudent;
数据的插入
在构造map容器之后,我们就可以往里面插入数据了。
方法1:用insert函数插入pair数据。
map<int,string> mmap;
mmap.insert(pair<int,string>(5,"Bill"));
方法2:用数组方式插入数据
#include <cstdio>
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<int,string> mmap;
mmap[1] = "Lucy";//用数组方式插入数据
mmap[2] = "Bill";
mmap[3] = "Utada";
map<int,string>::iterator it;
for(it = mmap.begin() ; it != mmap.end() ; it ++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
注意
用insert函数如果发现map中已经含有了该键值,则不会更新数据,直接跳过。
用数组方式插入数据则会更新数据。
map的大小
int nsize = mmap.size()
map的遍历
①使用正向迭代器
map<int,string>::iterator it;
for(it = mmap.begin() ; it != mmap.end() ; it ++) {
cout << it->first << " " << it->second << endl;
}
②使用反向迭代器
map<int,string>::reverse_iterator it;
for(it = mmap.rbegin() ; it != mmap.rend() ; it ++) {
cout << it->first << " " << it->second << endl;
}
③用数组的方式
int nSize = mmap.size();
for(int s = 1 ; s <= nSize ; s ++) {//注意是1-nSize
cout << mmap[s] << endl;
}
数据的查找
这就是map在数据插入时保证有序的好处。
两种数据查找方法:
①用conut函数来判定关键字是否出现,但无法定位位置。count返回0或1.
mmap.insert(pair<int,string>(1,"Bill"));
mmap.insert(pair<int,string>(2,"Utada"));
cout << mmap.count(2) << endl;//1
cout << mmap.count(3) << endl;//0
②使用find()函数定位数据位置。当数据出现时,它返回数据所在位置的迭代器。
mmap.insert(pair<int,string>(1,"Bill"));
mmap.insert(pair<int,string>(2,"Utada"));
mmap.insert(pair<int,string>(3,"Geller"));
map<int,string>::iterator it;
for(it = mmap.find(2) ; it != mmap.end() ; it ++) {
cout << it->first << " " << it->second << endl;
}
数据的清空和判空
map.clear();//清空
map.empty()//判空
数据的删除
erase函数可以删除map中的元素。
map<int,string>::iterator it;
it = mmap.find(1);
mmap.erase(it);//用迭代器删除了1 方法1
mmap.erase(1);//直接用键值删除 方法2
自定义比较函数
#include <cstdio>
#include <map>
#include <string>
#include <iostream>
using namespace std;
struct Stu {
int num;
string name;
bool operator < (Stu const &a) const {
return num < a.num;
}
};
int main()
{
map<Stu,int> mmap;
Stu a; a.num = 1 ; a.name = "Bill";
Stu b; b.num = 2 ; b.name = "Utada";
mmap.insert(pair<Stu,int>(a,1));
mmap.insert(pair<Stu,int>(b,2));
map<Stu,int>::iterator it;
for(it = mmap.begin() ; it != mmap.end() ; it ++) {
cout << it->second << " " << it->first.name << endl;
}
return 0;
}
本文详细介绍了C++ STL中的map容器,包括其特点、如何定义、数据的插入与查找方法、遍历方式以及如何使用自定义比较函数等内容。
904

被折叠的 条评论
为什么被折叠?



