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);}測試結果

新聞熱點
疑難解答