C++ set容器

set 容器

#include <iostream>
#include <set>
#include <algorithm>


/*
 set 容器
 set 根据元素的值,自动排序,重复元素会自动去重
 list不支持随机访问,不支持下标运算符
 支持各种迭代器和算法
*/

// 使用函数模板
template <typename T>
void display(const std::set<T> &arr){
    // 打印 array 数组内的元素
    for (const auto &i: arr)
        std::cout << i << " ";

    std::cout << std::endl;
}




void test1()
{
    std::set<int> s1 {1, 2, 3, 4, 5};

    s1 = {6, 7, 7, 1, 1, 5, 4, 3, 4, 4, 5, 5, 5, 5};  // 自动 排序 去重
    display(s1);

    s1.insert(10); // 插入

    // 查找元素 是否存在
    if (s1.count(10))  // 返回值 1为找到 0为未找到
        std::cout << "已找到" << std::endl;
    else
        std::cout << "未找到" << std::endl;
    
    // 查询元素
    auto it = s1.find(10);
    if (it !=s1.end())
        std::cout << "已找到" << *it << std::endl;
    
    s1.clear();  // 可以清空
}

void test2()
{
    std::set<std::string> s1 {"A", "B", "C", "D", "E"};
    // 插入元素:返回值 迭代器、是否正常插入
    auto result = s1.insert("F");
    // 设置 输出bool值
    std::cout << std::boolalpha;
    std::cout << "first:" << *(result.first) << std::endl;  // 查看插入内容
    std::cout << "second:" << result.second << std::endl;   // 插入成功 返回teue

    result = s1.insert("A");
    std::cout << std::boolalpha;
    std::cout << "first:" << *(result.first) << std::endl;  // 查看插入内容
    std::cout << "second:" << result.second << std::endl;   // 插入失败 返回False
}
int main()
{

    // test1();
    test2();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值