STL中的set和map在它们都使用Red Black Tree(一种自平衡BST)的意义上是相似的。请注意,搜索,插入和删除的时间复杂度为O(Log n)。
差异:
设置的差异仅用于存储键,而map用于存储键值对。例如,考虑在打印排序的不同元素的问题中,我们使用set,因为键需要有值。虽然如果我们将问题更改为打印不同排序元素的频率,则可以使用map。我们需要映射以将数组值存储为键,将频率存储为值。
// CPP program to demonstrate working of set
#include
using namespace std;
int main()
{
set s1;
s1.insert(2);
s1.insert(5);
s1.insert(3);
s1.insert(6);
cout << "Elements in set:\n";
for (auto it : s1)
cout << it << " "; // Sorted
return 0;
}
输出:
Elements in set:
2 3 5 6
// CPP program to demonstrate working of map
#include
using namespace std;
int main()
{
map m;
m[1] = 2; // Insertion by indexing
// Direct pair insertion
m.insert({ 4, 5 });
// Insertion of pair by make_pair
m.insert(make_pair(8, 5));
cout << "Elements in map:\n";
for (auto it : m)
cout << "[ " << it.first << ", "
<< it.second << "]\n"; // Sorted
return 0;
}
输出:
Elements in map:
[ 1, 2]
[ 4, 5]
[ 8, 5]
集和地图的变化:
设置和映射都存储唯一值和排序值。但是,如果我们没有这样的要求,则可以使用multiset / multimap和unordered_set / unoredred_map。
Multimap :Multimap不允许通过索引存储元素。
// CPP program to demonstrate working of Multimap
#include
using namespace std;
int main()
{
multimap m;
m.insert({ 1, 2 });
m.insert({ 2, 3 });
m.insert({ 4, 5 });
m.insert({ 2, 3 });
m.insert({ 1, 2 });
cout << "Elements in Multimap:\n";
for (auto it : m)
cout << "[ " << it.first << ", "
<< it.second << "]\n"; // Sorted
return 0;
}
输出:
Elements in Multimap:
[ 1, 2]
[ 1, 2]
[ 2, 3]
[ 2, 3]
[ 4, 5]
多重集:
// CPP program to demonstrate working of Multiset
#include
using namespace std;
int main()
{
multiset ms;
ms.insert(1);
ms.insert(3);
ms.insert(4);
ms.insert(2);
ms.insert(2);
cout << "Elements in Multiset:\n";
for (auto it : ms)
cout << it << " ";
return 0;
}
输出:
Elements in Multiset:
1 2 2 3 4
Unordered_set :
// CPP program to demonstrate working of Unordered_set
#include
using namespace std;
int main()
{
unordered_set us;
us.insert(1);
us.insert(3);
us.insert(4);
us.insert(2);
us.insert(2);
cout << "Elements in unordered_set:\n";
for (auto it : us)
cout << it << " "; // Sorted
return 0;
}
输出:
Elements in unordered_set:
2 4 1 3
Unordered_map :
// CPP program to demonstrate working of Unordered_map
#include
using namespace std;
int main()
{
unordered_map um;
um[1] = 2;
um[4] = 5;
um[2] = 3;
um[8] = 5;
um[3] = 6;
cout << "Elements in unordered_map:\n";
for (auto it : um)
cout << "[ " << it.first << ", " << it.second << "]\n";
return 0;
}
输出:
Elements in unordered_map:
[ 3, 6]
[ 2, 3]
[ 8, 5]
[ 1, 2]
[ 4, 5]
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。