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

在 C++ 中,可以使用 std::set 容器来存储唯一元素使用 find() 成员函数:#include #include int main() {std::set my_set = {1, 2, 3, 4, 5};int target = 3;auto it = my_set.find(target);if (it != my_set.end())

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。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1201440.html

(0)
派派
上一篇 2024-11-29
下一篇 2024-11-29

发表回复

登录后才能评论