C++ STL 中的 Set vs Map
Set 是一個抽象資料型別,每個元素都必須唯一,因為元素的值標識了該元素。元素的值一旦新增到 set 中就無法修改,但可以刪除該元素並新增其修改後的值。
Map 是一個關聯容器,按對映方式儲存元素。每個元素都具有一個鍵值和一個對映值。沒有兩個對映值可以具有相同的鍵值。
因此,從上面可以清楚地看出,set 僅包含鍵,map 則包含帶有鍵的值,兩者都應具有唯一且經過排序的值。
對於無序且未排序的元素,有無序_set/無序_map、多重set/多重map。
示例程式碼
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s; //initializing a empty set container
set<int>::iterator it; //Initializing a set container as iterator
s.insert(7); //inserting elements in the set container s
s.insert(6);
s.insert(1);
s.insert(4);
s.insert(2);
s.insert(9);
s.insert(10);
cout << "Elements are in set:\n";
for ( auto it : s)
cout << it << " "; //printing elements of the set container
return 0;
}輸出
1 2 4 6 7 9 10
示例程式碼
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<char, int> m; //initialize a map
map<char, int>::iterator iter; //initializing a map as iterator
m.insert (pair<char, int>('a', 10)); //inserting values to the map
m.insert (pair<char, int>('b', 20));
cout << "Elements in map:\n";
for (iter=m.begin();iter!=m.end();iter++)
cout << "[ " << iter->first << ", "<< iter->second << "]\n"; //printing the values of the map
return 0;
}輸出
Elements in map: [ a, 10] [ b, 20]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP