温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

初探C++ set函数,掌握基本用法

发布时间:2024-08-05 18:20:06 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在C++中,set是一种容器,用来存储不重复的元素,并且会自动进行排序。set是基于红黑树实现的,因此插入、查找和删除操作的时间复杂度都是O(logn)。

下面是set的基本用法示例:

#include <iostream>
#include <set>

int main() {
    // 创建一个set
    std::set<int> myset;

    // 插入元素
    myset.insert(3);
    myset.insert(1);
    myset.insert(5);

    // 遍历set
    for (auto it = myset.begin(); it != myset.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // 查找元素
    if (myset.find(3) != myset.end()) {
        std::cout << "3 is found in the set" << std::endl;
    }

    // 删除元素
    myset.erase(1);

    // 遍历set
    for (int x : myset) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}

在上面的示例中,我们首先创建了一个set,并插入了元素3、1和5。然后遍历了set中的元素,并查找了元素3。接着删除了元素1,并再次遍历了set。

需要注意的是,set中的元素是按照默认的升序排序的。如果要使用自定义的比较函数来排序,可以在创建set时传入自定义的比较函数,例如:

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

std::set<int, cmp> myset;

这样就可以实现降序排序的set。至此,我们初步探究了C++中set的基本用法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI