您的位置:首页 > 编程语言 > C语言/C++

C++ STL学习之九:关联式容器map深入学习

2014-07-02 17:26 302 查看
MAP容器

1)概念:map 是一个容器,它用于储存数据并且能从一个数据集合中取出数据。它的数据组成包含两项,一个是它的数据值,一个是用于排序的关键字。其中关键字是惟一的,它用于将数据自动排序。而每个元素的数据值与关键字无关,可以直接改变。

【重点】内部结构采用RB_TREE(红黑树)。查找复杂度:O(log2N)

multimap 跟map 特性相同,唯一的区别是允许键值重复!!!

2)使用

需加载的头文件: #include<map>

using namespace std;

模板原型:

template <

class Key, //关键字的数据类型

class Type, //数据值的数据类型

class Traits = less<Key>, //提 供 比 较 两 个 元 素 的 关 键 字 来 决 定 它 们 在 map容器中的相对位置。它是可选的,它的默认值是 less<key>

class Allocator=allocator<pair <const Key, Type> > //代表存储管理设备。它是可选的,它的默认值为allocator<pair <const Key, Type> >

>

3)map 容器特点:

(1)是一个相关联的容器,它的大小可以改变,它能根据关键字来提高读取数据能力。

(2)提供一个双向的定位器来读写取数据。

(3)已经根据关键字和一个比较函数来排好序。

(4)每一个元素的关键字都是惟一的。

(5)是一个模板,它能提供一个一般且独立的数据类型。

关联式容器map的特性是:所有的元素的键值都会被自动排序,默认排序是升序,注意map的所有元素类型是pair。

我们可以通过map的迭代器来改变其指向的元素值。标准的STLmap采用RB-tree作为底层的实现机制。每个节点的一个元素都是一个pair。

#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(int argc,char *argv[])
{
<span style="white-space:pre">	</span>map<string,int> mymap;
<span style="white-space:pre">	</span>map<string,int>::iterator iter;
<span style="white-space:pre">	</span>string str[]={"shen","hua","hust","shen","shen","yu"};
<span style="white-space:pre">	</span>for(int i=0;i<6;i++)//这样也可以构造map
<span style="white-space:pre">		</span>mymap[str[i]]++;
<span style="white-space:pre">	</span>for(iter=mymap.begin();iter!=mymap.end();iter++)//遍历map
<span style="white-space:pre">		</span>cout<<"("<<iter->first<<","<<iter->second<<")"<<endl;
<span style="white-space:pre">	</span>cout<<endl;

<span style="white-space:pre">	</span>pair<string,int> tpair(string("shenhuayu"),10);//构造键值对
<span style="white-space:pre">	</span>mymap.insert(tpair);//将键值对插入map中
<span style="white-space:pre">	</span>for(iter=mymap.begin();iter!=mymap.end();iter++)
<span style="white-space:pre">		</span>cout<<"("<<iter->first<<","<<iter->second<<")"<<endl;
<span style="white-space:pre">	</span>cout<<endl;

<span style="white-space:pre">	</span>iter=mymap.find("shen");//find查找键值
<span style="white-space:pre">	</span>if(iter==mymap.end())
<span style="white-space:pre">		</span>cout<<"not found!"<<endl;
<span style="white-space:pre">	</span>else
<span style="white-space:pre">		</span>cout<<"found it!"<<endl;
<span style="white-space:pre">	</span>cout<<endl;

<span style="white-space:pre">	</span>iter->second=19999;//直接可以修改实值
<span style="white-space:pre">	</span>for(iter=mymap.begin();iter!=mymap.end();iter++)
<span style="white-space:pre">		</span>cout<<"("<<iter->first<<","<<iter->second<<")"<<endl;
<span style="white-space:pre">	</span>cout<<endl;
<span style="white-space:pre">	</span>return 0;
}


shenhuayu@shenhuayu-VirtualBox ~/src $ ./mystltest

(hua,1)

(hust,1)

(shen,3)

(yu,1)

(hua,1)

(hust,1)

(shen,3)

(shenhuayu,10)

(yu,1)

found it!

(hua,1)

(hust,1)

(shen,19999)

(shenhuayu,10)

(yu,1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: