C++ STL中的Set vs Map

Set vs Map in C++ STL

Set是一种抽象数据类型,其中每个元素都必须是唯一的,因为元素的值可以标识它。 一旦将元素的值添加到集合中,就无法对其进行修改,但是可以删除并添加该元素的修改后的值。

映射是一个关联容器,以映射方式存储元素。 每个元素都有一个键值和一个映射值。 任何两个映射值都不能具有相同的键值。

因此,从上方可以清楚地看到,set包含唯一的键,而map包含带有键的值,两者都应具有唯一值和排序值。

对于无序和未排序的元素,有unordered_set / unordered_map,multiset / multimap。

范例程式码

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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:
";
 for ( auto it : s)
   cout << it <<""; //printing elements of the set container
 return 0;
}

输出量

1
1 2 4 6 7 9 10

范例程式码

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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:
";
 for (iter=m.begin();iter!=m.end();iter++)
 cout <<"[" << iter->first <<","<< iter->second <<"]
"; //printing the values of the map
 return 0;
}

输出量

1
2
3
Elements in map:
[ a, 10]
[ b, 20]