在 C++ 中,可以使用 std::set 容器来存储唯一元素
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;
}
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。