set的使用方法

在 C++中,STL(标准模板库)中的 std::set 是一种关联容器,它存储的元素是唯一的,且不能通过迭代器修改,只能删除了然后插入,并且按照一定的严格弱序排列。


以下是 std::set 的一些常见使用方法及示例:

 一、头文件包含

#include <set>

二、创建和初始化


 1. 创建一个空的 set :

std::set<int> mySet;

2. 使用初始化列表初始化 set :

std::set<int> mySet = {1, 2, 3, 4, 5};

三、基本操作


 1. 插入元素:

mySet.insert(6);


2. 删除元素:


- 根据值删除:

mySet.erase(3);

- 根据迭代器删除:

std::set<int>::iterator it = mySet.find(4);
if (it!= mySet.end()) {
    mySet.erase(it);
}


3. 查找元素:

std::set<int>::iterator it = mySet.find(2);
if (it!= mySet.end()) {
    std::cout << "元素 2 存在于 set 中。" << std::endl;
} else {
    std::cout << "元素 2 不存在于 set 中。" << std::endl;
}


4. 获取元素数量:

int size = mySet.size();


5. 判断是否为空:
 

bool isEmpty = mySet.empty();

四、遍历


 1. 使用迭代器遍历:

for (std::set<int>::iterator it = mySet.begin(); it!= mySet.end(); ++it) {
    std::cout << *it << " ";
}
std::cout << std::endl;

2. 使用范围 for 循环遍历:
 

for (int value : mySet) {
    std::cout << value << " ";
}
std::cout << std::endl;

五、其他操作


 
1. 合并两个 set :

std::set<int> mySet = {1, 2, 3, 4, 5};
std::set<int> anotherSet = {7, 8, 9};
mySet.insert(anotherSet.begin(), anotherSet.end());


 六、举例

如下举例展示 std::set 的一些常见操作,包括插入、删除、查找、遍历和合并

#include <iostream>
#include <set>

int main() {
    std::set<int> mySet = { 2, 4, 6 };

    //插入一个已经存在的元素
    mySet.insert(2);

    // 插入元素
    mySet.insert(8);

    // 删除元素
    mySet.erase(4);

    // 查找元素
    std::set<int>::iterator it = mySet.find(6);
    if (it != mySet.end()) {
        std::cout << "找到元素 6。" << std::endl;
    }

    // 遍历并输出
    for (int value : mySet) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    // 合并另一个 set
    std::set<int> anotherSet = { 1, 3, 5 };
    mySet.insert(anotherSet.begin(), anotherSet.end());

    // 再次遍历并输出
    for (int value : mySet) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    return 0;
}

输出结果:

找到元素 6。
2 6 8
1 2 3 5 6 8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值