国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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);}

測試結果


上一篇:牛頓迭代公式

下一篇:面向對象基礎

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿城市| 治县。| 呼玛县| 贡觉县| 黄大仙区| 金秀| 科尔| 丹巴县| 息烽县| 长阳| 区。| 应用必备| 房产| 肇州县| 塔河县| 彰化县| 集安市| 陵川县| 林州市| 汽车| 江源县| 淄博市| 台南市| 鹿泉市| 丰镇市| 嘉善县| 曲阜市| 阿城市| 天镇县| 来安县| 浮梁县| 浦县| 洱源县| 贵州省| 滨海县| 石渠县| 资源县| 郑州市| 平安县| 玉门市| 曲周县|