c++ set实现方法

  • 格式:docx
  • 大小:16.10 KB
  • 文档页数:6

c++ set实现方法

摘要:

1.C++ Set概述

2.C++ Set实现方法

a.STL内置set

b.自定义set

3.Set容器常用操作

a.插入元素

b.删除元素

c.查找元素

d.遍历元素

4.应用场景及示例

5.总结与展望

正文:

C++ Set实现方法

1.C++ Set概述

C++ Set是一种基于红黑树(RB-Tree)的关联容器,用于存储键值对(key-value)集合。Set中的元素具有唯一性,即不存在重复的键。Set容器提供了许多实用的操作,如插入、删除、查找等。

2.C++ Set实现方法

a.STL内置set C++标准库提供了内置的set容器,可以直接使用。内置set实现了高效的插入、删除和查找操作,同时还支持自定义比较函数。

b.自定义set

如果需要对set容器进行二次开发或定制,可以自行实现set容器。自定义set的实现方法有很多,这里以红黑树为例,简要介绍如何实现一个基本的set容器。

```cpp

#include

#include

#include

template

class CustomSet {

public:

using KeyType = T;

using ValueType = std::pair;

CustomSet() = default;

void insert(const KeyType &key) {

// 插入元素

}

void erase(const KeyType &key) {

// 删除元素

} bool find(const KeyType &key) const {

// 查找元素

}

void print() const {

// 遍历元素

}

private:

using Node = std::pair>;

Node *root_ = nullptr;

Node *findNode(const KeyType &key) const {

// 查找节点

}

Node *insert(Node *node, const KeyType &key) {

// 插入节点

}

Node *erase(Node *node, const KeyType &key) {

// 删除节点

}

void printNode(Node *node, int level) const {

// 遍历节点

}

}; ```

3.Set容器常用操作

a.插入元素

```cpp

set s;

s.insert(1);

s.insert(2);

```

b.删除元素

```cpp

s.erase(1);

```

c.查找元素

```cpp

auto it = s.find(2);

if (it != s.end()) {

std::cout << "找到元素:" << *it << std::endl;

}

```

d.遍历元素

```cpp

for (const auto &element : s) { std::cout << "元素:" << element << std::endl;

}

```

4.应用场景及示例

Set容器适用于需要保证元素唯一性的场景,如计数、字典等。以下是一个简单的示例,用于存储用户信息:

```cpp

#include

#include

#include

using namespace std;

int main() {

set> users;

users.insert({"Alice", 25});

users.insert({"Bob", 30});

users.insert({"Alice", 25}); // 插入相同键值,重复键值会被忽略

cout << "用户数量:" << users.size() << endl;

cout << "查找Bob:" << boolalpha << users.find("Bob") !=

users.end() << endl;

users.erase("Bob");

cout << "删除Bob后,用户数量:" << users.size() << endl;

return 0; }

```

5.总结与展望

C++ Set容器是一种高效、易用的数据结构,适用于许多场景。