c++关联容器的成员函数find的一个例子

 先来一个灰色难懂的部分镇楼。

#include <string>
#include <iostream>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <utility>
#include <algorithm>
using namespace std;
int main()
{
set<int> iset = {0,1,2,3,4,5,6,7,8,9};
set<int>::iterator pos1 = iset.find(1);
cout << *pos1 << endl;
auto pos2 = iset.find(11);
if(pos2 == iset.end())
        cout<< "yes" << endl;
auto n = iset.count(1);
cout << n << endl;
auto n1 = iset.count(11);
cout << n1 << endl;
        
multimap<string,size_t> m1{
  
  {"abc",1},{"abc",2},{"abcd",3}};
auto pos3 = m1.find("abc");
if(pos3 == m1.end())
        cout << "end"<< endl;
else 
        cout << 
### C++ 中 `map` 容器的 `find` 函数使用方法 在 C++ 的标准库中,`std::map` 提供了一个名为 `find` 的成员函数,该函数用于在一个映射表中查找指定键是否存在。如果找到对应的键,则返回指向该键值对的迭代器;如果没有找到,则返回 `end()` 迭代器。 以下是关于 `find` 函数的具体说明以及示例代码: #### 基本语法 ```cpp iterator find(const key_type& k); const_iterator find(const key_type& k) const; ``` - 参数 `k` 表示要查找的键。 - 如果找到了键 `k`,则返回一个指向键值对的迭代器。 - 若未找到,则返回 `map.end()`[^2]。 #### 返回值解释 - 当调用成功时,返回的是一个指向目标键值对的迭代器。 - 调用失败时,返回的是容器中的特殊迭代器 `end()`,表示超出范围的位置。 #### 示例代码 下面是一个完整的例子展示如何使用 `find` 方法来定位特定键并访问其关联的值。 ```cpp #include <iostream> #include <map> int main() { // 创建一个 map 并初始化一些数据 std::map<int, std::string> myMap = { {1, "Apple"}, {2, "Banana"}, {3, "Cherry"} }; // 查找键为 2 的元素 auto it = myMap.find(2); if (it != myMap.end()) { std::cout << "Key found: " << it->first << ", Value: " << it->second << std::endl; } else { std::cout << "Key not found!" << std::endl; } // 尝试查找不存在的键 auto missingIt = myMap.find(4); if (missingIt == myMap.end()) { std::cout << "Key 4 is not present in the map." << std::endl; } } ``` 上述程序展示了两个场景下的行为:当存在匹配项时打印对应的结果;而当找不到给定键的时候输出提示信息表明此键不在当前集合之中[^3]。 #### 注意事项 尽管这里讨论的是 `std::map` 上的操作,但是类似的逻辑也适用于其他基于键值存储的数据结构比如 `unordered_map` 等。不过需要注意不同类型的性能特点差异,在选择具体实现之前应该考虑清楚需求背景再做决定[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

发狂的蜗牛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值