当我们处理数据时,有时需要使用一些高效的数据结构来存储和管理元素。在C++中,我们有许多与此相关的容器类,如 树型结构:set,map,multiset,multimap; 哈希结构: unordered_set和unordered_map。这些容器提供了不同的特性和适用性,下面我们将逐个介绍它们。
1. set:
set是一个有序的容器,它只包含唯一的元素。当我们需要存储一组元素,并确保没有重复值时,set是一个很好的选择。它基于红黑树实现,因此插入、删除和查找操作的时间复杂度都是O(log n)。set的元素按升序排列。
#include <iostream>
#include <set>
using namespace std;
int main() {
// 创建一个set容器
set<int> mySet;
// 插入元素
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
// 查找元素
int key = 20;
auto it = mySet.find(key);
if (it != mySet.end()) {
cout << key << " is found in the set." << endl; // 20 is found in the set.
}
else {
cout

最低0.47元/天 解锁文章
1309

被折叠的 条评论
为什么被折叠?



