在set容器中利用find()和end()查找元素的简单使用

以下是利用容器set的begin()end()以及find()函数来打印元素并查找元素的简单代码示例

#include 
#include 

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

    std::cout<<"Elements in the set:";
    auto it=mySet.begin();
    while (it != mySet.end())
    {
        std::cout<<*it<< "  " ;
        it++;
    }
    std::cout<<std::endl;

    // 查找元素
    auto endIter = mySet.end();
    std::cout << "end iter add =" << &(*endIter) << std::endl;

    std::cout<<"查找元素3"<<std::endl;
    auto found = mySet.find(3);
    std::cout << "found=" << &(*found) << std::endl;


   // 检查元素是否存在
    if (found != mySet.end()) {
        std::cout << "元素存在: " << *found << std::endl;
    } else {
        std::cout << "元素不存在." << std::endl;
    }

    // 尝试查找不存在的元素
    auto notFound = mySet.find(10);
    std::cout<<"查找元素10"<<std::endl;
    std::cout << "notFound=" << &(*notFound) << std::endl;



    if (notFound != mySet.end()) {
        std::cout << "元素存在: " << *notFound << std::endl;
    } else {
        std::cout << "元素不存在." << std::endl;
    }

    return 0;
}

输出结果:
Elements in the set:1  2  3  4  5  
end iter add =0x7ffd078f22d8
查找元素3
found=0x557845dec330
元素存在: 3
查找元素10
notFound=0x7ffd078f22d8
元素不存在.

上面代码中因为 std::set::find() 在找到元素时返回指向该元素的迭代器,而在未找到时返回集合的末尾迭代器(mySet.end())
所以 found 指向元素 3 的迭代器,而 notFound 指向集合的末尾迭代器。

你可能感兴趣的:(基于Linux的C++,数据结构,算法,c++,算法,开发语言)