c++ 中的 set 如何判断元素是否存在

在 C++ 的 set 容器中,你可以使用 find() 成员函数来判断一个元素是否已经存在。如果 find() 返回的迭代器等于 set 的 end() 迭代器,那么说明该元素不存在;否则,该元素存在于 set 中。以下是一个示例代码:#include #include using namespace std;int main() {set my_

C++set 容器中,你可以使用 find() 成员函数来判断一个元素是否已经存在。如果 find() 返回的迭代器等于 setend() 迭代器,那么说明该元素不存在;否则,该元素存在于 set 中。

以下是一个示例代码:

#include <iostream>
#include <set>
using namespace std;

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

    int target = 6;
    if (my_set.find(target) == my_set.end()) {
        cout << target << " is not in the set." << endl;
    } else {
        cout << target << " is in the set." << endl;
    }

    return 0;
}

在这个示例中,我们创建了一个包含整数的 set,然后使用 find() 函数查找一个不存在的元素 6。因为 6 不在 set 中,所以 find() 返回的迭代器等于 setend() 迭代器,我们输出 “6 is not in the set.”。

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

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

发表回复

登录后才能评论