在C++中,`set`是STL标准库中的一个关联容器,用于存储不重复的元素,并且这些元素会自动按键值进行排序。以下是一些基本用法:
创建set容器 ```cpp
include include
int main() {
std::set mySet; // 创建一个空的整数集合 return 0;
}
```
插入元素
include
int main() {
std::set return 0; } ``` 插入元素
```cpp
mySet.insert(5);
mySet.insert(10);
mySet.insert(1);
```
遍历集合
```cpp
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
```
查找元素
```cpp
if (mySet.find(3) != mySet.end()) {
std::cout << "3 is found in the set" << std::endl;
} else {
std::cout << "3 is not found in the set" << std::endl;
}
```
删除元素
```cpp
mySet.erase(1);
```
检查元素是否存在
```cpp
if (mySet.count(5) > 0) {
std::cout << "Element 5 is in the set." << std::endl;
} else {
std::cout << "Element 5 is not in the set." << std::endl;
}
```
建议
使用STL的set: C++标准库中的`set`是一个功能强大且易于使用的容器,建议优先使用。 自定义实现
希望这些示例和解释对你有所帮助!