当前位置: 首页 > news >正文

FX-std::set

std::set 是 C++ 标准库中的一个关联容器,用于存储唯一元素,并按照特定顺序进行排序。它基于红黑树实现,因此插入、删除和查找操作的时间复杂度均为 O(log n)。以下是 std::set 的基本用法:

1. 包含头文件

#include <set>

2. 声明和初始化

std::set<int> mySet; // 声明一个存储 int 类型的 set

3. 插入元素

mySet.insert(10);
mySet.insert(20);
mySet.insert(30);

4. 删除元素

mySet.erase(20); // 删除值为 20 的元素

5. 查找元素

auto it = mySet.find(10);
if (it != mySet.end()) {
    std::cout << "Element found: " << *it << std::endl;
} else {
    std::cout << "Element not found" << std::endl;
}

6. 遍历元素

for (const auto& elem : mySet) {
    std::cout << elem << std::endl;
}

7. 获取大小

std::cout << "Size of set: " << mySet.size() << std::endl;

8. 检查是否为空

if (mySet.empty()) {
    std::cout << "Set is empty" << std::endl;
} else {
    std::cout << "Set is not empty" << std::endl;
}

9. 清空 set

mySet.clear();

10. 自定义排序规则

struct MyCompare {
    bool operator()(int a, int b) const {
        return a > b; // 降序排序
    }
};

std::set<int, MyCompare> myCustomSet;
myCustomSet.insert(10);
myCustomSet.insert(20);
myCustomSet.insert(30);

for (const auto& elem : myCustomSet) {
    std::cout << elem << std::endl; // 输出: 30, 20, 10
}

11. 其他常用操作

  • lower_bound: 返回第一个不小于给定值的元素的迭代器。

  • upper_bound: 返回第一个大于给定值的元素的迭代器。

  • equal_range: 返回一个包含所有等于给定值的元素的范围。

auto low = mySet.lower_bound(15);
auto high = mySet.upper_bound(25);

for (auto it = low; it != high; ++it) {
    std::cout << *it << std::endl;
}

12. 注意事项

  • std::set 中的元素是唯一的,插入重复元素不会改变集合。

  • std::set 中的元素是有序的,默认是升序排列。

示例代码

#include <iostream>
#include <set>

int main() {
    std::set<int> mySet;

    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);
    mySet.insert(20); // 重复元素,不会被插入

    for (const auto& elem : mySet) {
        std::cout << elem << " "; // 输出: 10 20 30
    }

    mySet.erase(20);

    if (mySet.find(20) == mySet.end()) {
        std::cout << "\n20 not found in set" << std::endl;
    }

    return 0;
}

std::set 是一个非常强大的容器,适用于需要快速查找和有序存储的场景。

相关文章:

  • LLM的准确率评估采用什么方式:准确率评估使用的是 `sklearn.metrics` 模块中的 `accuracy_score` 函数
  • 日常开发记录-radioGroup组件
  • 【并发编程】JUC常用类以及线程池
  • 在Simulink中将Excel数据导入可变负载模块的方法介绍
  • Docker Swarm 集群操作实践
  • django框架 [面试篇]
  • python-leetcode-最大连续1的个数 III
  • 【leetcode hot 100 146】LRU缓存
  • 如何修复 Tauri 发布后程序运行时显示 `asset not found: index.html` 的问题
  • 父组件中循环生成多个子组件时,有且只有最后一个子组件的watch对象生效问题及解决办法
  • NFS writeback流程中的GFP_NOFS
  • Docker安装部署RabbitMQ
  • 条款1:理解模版性别推导
  • C#带多组标签的Snowflake SQL查询批量数据导出程序
  • linux 命令 grep
  • Embedding模型到底是什么?
  • C++11 编译使用 aws-cpp-sdk
  • 专题地图的立体表达-基于QGIS和PPT的“千层饼”视图制作实践
  • 后端主流数据库分析
  • 前端面试:React生态有哪些?
  • 舞蹈网站建设报价/株洲网站设计外包首选
  • 返利网站怎么做的/代写
  • 求网站开发客户/google关键词推广
  • 南山做棋牌网站建设/seo基础知识培训
  • 宁波网站建设风格/seo的优化方案
  • 做视频网站推广/市场营销计划书模板