【C++】unordered_set中find()用法及代码示例

本文介绍了C++ STL中unordered_set容器的find()函数,用于在无序集合中查找元素。如果找到元素,函数返回其迭代器;否则,返回end()迭代器。示例程序展示了如何使用find()检查元素是否存在,以及找不到元素时的输出情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unordered_set::find()函数是C++ STL中的内置函数,用于在容器中搜索元素。如果找到指定元素,它返回元素的迭代器,如果找不到指定元素,则返回指向unordered_set::end()的迭代器

用法:

unordered_set_name.find(key)

参数:此函数接受必需的参数键,该键指定要搜索的元素。

返回值:返回找到元素的迭代器,否则返回指向unordered_set末尾的迭代器。

以下示例程序旨在说明unordered_set::find()函数:

示例1:

#include <iostream> 
#include <string> 
#include <unordered_set> 
  
using namespace std; 
  
int main() 
{ 
  
    unordered_set<string> sampleSet = { "geeks1", "for", "geeks2" }; 
  
    // use of find() function 
    if (sampleSet.find("geeks1") != sampleSet.end()) { 
        cout << "element found." << endl; 
    } 
    else { 
        cout << "element not found" << endl; 
    } 
  
    return 0; 
}

输出:

element found.

示例2:

#include <iostream> 
#include <string> 
#include <unordered_set> 
  
using namespace std; 
  
int main() 
{ 
  
    unordered_set<string> sampleSet = { "geeks1", "for", "geeks2" }; 
  
    // use of find() function 
    if (sampleSet.find("geeksforgeeks") != sampleSet.end()) { 
        cout << "found" << endl; 
    } 
    else { 
        cout << "Not found" << endl; 
    } 
  
    return 0; 
}

输出:

Not found
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Quentin_HIT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值