首页 > 学院 > 开发设计 > 正文

STL中的SET与MAP

2019-11-08 18:51:43
字体:
来源:转载
供稿:网友

SET.MAP的特性与区别

        set与map一样都是属于STL里的关联式容器。

        set包含了经过排序了的数据即键值(key),这些数据的值必须是唯一的。set所有的元素放入是无顺序的,在set中都会根据元素的键值自动排序。所以在STL中set是以RB-TREE为底层机制。

        map就是经过排序了的二元组的集合,map中的每个元素都是由两个值组成,键值(key)与实值(value),其中键值唯一同样所有元素都会根据键值自动被排序。所以map的所有元素都由一种叫pair的结构实现存储,map在STL中pair的定义如下:

template<class K,class V>struct pair {	typedef K first_type;	typedef V second_type;	K first;	V second;	pair()		:first(K())		,second(V())	{}	pair(const K& a, const V& b)		:first(a)		,second(b)	{}};

        简单来说set在STL中其结点是一个数据,而map是一对数据。

SET与MAP的应用场景

       如果你要查找一个元素是否在某集合内存中,则可以选择使用set,应为此时set集合的属性可以完成此项任务且节省空间与时间。

        map因为是KV结构,你存储的元素可以通过key值访问到其value值,所以当你如果要存储一个数据字典时,要求方便的根据key找value,那么选map。

SET与MAP的使用实例

SET

#include<iostream>#include<set>using namespace std;int main(){    set<int> myset;    myset.insert(0);    myset.insert(8);    myset.insert(9);    myset.insert(6);    myset.insert(4);    set<int>::iterator it;    for(it = myset.begin(); it != myset.end(); it++){        cout<< *it;      }}输出结果

MAP(统计水果出现的次数)

#include<iostream>#include<map>using namespace std;void countMap(string strs[], size_t sz)  {	map <string, int> count;	for (size_t i = 0; i < sz; ++i)	{		map <string,int>::iterator it = count.find(strs[i]);  		  if (it != count.end())  		  {  		      it->second++;   		  }  		  else  		  {  		      count.insert(pair<string,int>(strs[i],1));  		  }  	}}int main() {	string strs[] = { "apple","apple","banana","orange","pineapple","grape",		"banana","orange","apple","apple","orange" };	size_t sz = sizeof(strs) / sizeof(strs[0]);	countMap(strs, sz);}

测试结果


上一篇:牛顿迭代公式

下一篇:面向对象基础

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表