【STL】STL容器之map

来源:互联网 发布:ubuntu使用yum gcc 编辑:程序博客网 时间:2024/04/28 03:16

        Map是一个关联容器,它内部有两个数据,第一个(first)称为关键字(key),第二个(second)称为关键字的值(value),keyvalue二者是一一对应的(称为pair),且keymap中关键字是唯一的。map内部自建一颗严格意义上的平衡二叉树,对数据有排序功能,因此,map内部数据都是有排序的(lessgreater)。

具体关于map容器类的介绍可以看这:https://msdn.microsoft.com/en-us/library/s44w4h2s.aspx

下面来看看一些常用的方法:

1、map::insert()

map<string, int> student;student.insert(pair<string, int>("xiaohong", 80));student.insert(pair<string, int>("xiaofang", 76));//成功student.insert(pair<string, int>("xiaoming", 94));student.insert(pair<string, int>("xiaozhang", 80));//key不同,value可以相同student.insert(pair<string, int>("xiaofang", 88));//存在为"xiaofang"的key,插入失效

实际上,mapinsert比较简单,因此不论你怎么插,其内部的平衡二叉树都会根据关键字key自动排序。在上述代码中可知,keystring类型的,且是唯一的,插入重复的关键字的一对数据将会失效;虽然key唯一,但是value可以相同。(上面可以看作是学生的考试成绩,姓名(key)与成绩(value)一一对应)

2、map::begin()、map::cbegin()、map::end()、map::cend()、

       map::crbegin()、map::crend()、map::rbegin()、map::rend()

这些就不说了。

3、map::at()、map::iterator(元素的访问)

map<string, int>::iterator it;for (it = student.begin(); it != student.end(); ++it){cout<<it->first<<" "<<it->second<<endl;}cout<<student.at("xiaoming")<<endl;cout<<student.at("xiaozhang")<<endl;
实际上,关键字key存放在map中为first,关键字的值valuemap中为second,使用的是迭代器来访问。

at()访问时,带入的参数是关键字,返回关键字所对应的值,上面的两个输出分别是:94、80。

4、map::count()

cout<<student.count("xiaohong")<<endl;//输出1cout<<student.count("xiaoHong")<<endl;//输出0

这个方法是用来判断map中是否存在某个关键字。存在返回1,不存在返回0
5、map::find()

map<string, int>::iterator it;it = student.find("xiaoming");cout<<it->first<<" "<<it->second<<endl;
查找,返回所查找关键字指向的迭代器。

6、map::equal_range()

pair<map<string, int>::iterator, map<string, int>::iterator> it;it = student.equal_range("xiaoho");cout<<it.first->first<<" "<<it.first->second<<endl;cout<<it.second->first<<" "<<it.second->second<<endl;
返回一对迭代器。第一个迭代器指向的是map中第一个大于key的迭代器,第二个迭代器指向的是map中第一个大于或等于key的迭代器。
7、map::erase()

student.erase("xiaofang");//删除关键字为"xiaofang"的pairstudent.erase(student.begin());//删除起始位置的pairstudent.erase(next(student.begin()), prev(student.end()));//保留第一个和最后一个pair,其余的全部删除

删除某个关键字所关联的pair of key-value或某个位置或某个连续位置pair of key-value
8、map::clear()、map::empty()、map::size()

student.clear();cout<<student.empty()<<endl;cout<<student.size()<<endl;

map::clear()是删除map中的所有pairmap::empty()返回一个bool类型值,true表示空,flase表示非空,map::size()返回mappair的个数。

9、其他的用法

vector<pair<string, int> >s;s.push_back(make_pair("ads", 3));s.push_back(make_pair("edf", 6));s.push_back(make_pair("ifd", 9));vector<pair<string, int>>::iterator iw;for(iw = s.begin(); iw != s.end(); ++iw){cout<<iw->first<<" "<<iw->second<<endl;}cout<<endl<<endl;student.insert(s.begin(), s.end());for (it = student.begin(); it != student.end(); ++it){cout<<it->first<<" "<<it->second<<endl;}
比如将vector转换成map来使用也是可以的。
当然,还有一些其他用法,用到的时候再查,这里就不介绍了。

0 0