首页主机资讯c++ 中的 set 如何查找元素

c++ 中的 set 如何查找元素

时间2025-09-27 15:27:03发布访客分类主机资讯浏览318
导读:在 C++ 中,可以使用 std::set 容器来存储唯一元素 使用 find( 成员函数: #include <iostream> #include <set> int main( { std::...

在 C++ 中,可以使用 std::set 容器来存储唯一元素

  1. 使用 find() 成员函数:
#include <
    iostream>
    
#include <
    set>


int main() {
    
    std::set<
    int>
 my_set = {
1, 2, 3, 4, 5}
    ;
    

    int target = 3;
    
    auto it = my_set.find(target);


    if (it != my_set.end()) {
    
        std::cout <
    <
     "Element " <
    <
     target <
    <
     " found in the set." <
    <
     std::endl;

    }
 else {
    
        std::cout <
    <
     "Element " <
    <
     target <
    <
     " not found in the set." <
    <
     std::endl;

    }
    

    return 0;

}
    
  1. 使用 count() 成员函数:
#include <
    iostream>
    
#include <
    set>


int main() {
    
    std::set<
    int>
 my_set = {
1, 2, 3, 4, 5}
    ;
    

    int target = 3;
    
    if (my_set.count(target) >
 0) {
    
        std::cout <
    <
     "Element " <
    <
     target <
    <
     " found in the set." <
    <
     std::endl;

    }
 else {
    
        std::cout <
    <
     "Element " <
    <
     target <
    <
     " not found in the set." <
    <
     std::endl;

    }
    

    return 0;

}
    

这两种方法都可以在 O(log n) 的时间复杂度内查找元素。find() 函数返回一个指向找到的元素的迭代器,如果未找到元素,则返回 end() 迭代器。count() 函数返回一个整数,表示元素在集合中出现的次数,如果元素不存在,则返回 0。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c++ 中的 set 如何查找元素
本文地址: https://pptw.com/jishu/710133.html
c++ 中的 set 如何删除元素 c++ 编译指令在不同平台的差异

游客 回复需填写必要信息