溫馨提示×

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

c++
小樊
136
2024-11-29 12:02:46
欄目: 編程語言

在 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。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女