std::set<Key,Compare,Allocator>::find
来自cppreference.com
iterator find(const Key& key ); | (1) | |
const_iterator find(const Key& key )const; | (2) | |
template<class K > iterator find(const K& x ); | (3) | (C++14 起) |
template<class K > const_iterator find(const K& x )const; | (4) | (C++14 起) |
1,2) 寻找键等价于 key 的的元素。
3,4) 寻找键比较等价于值 x 的元素。此重载只有在限定标识 Compare::is_transparent 合法并指代类型时才会参与重载决议。它允许调用此函数时无需构造
Key
的实例。目录 |
[编辑]参数
key | - | 要搜索的元素键值 |
x | - | 能透明地与键比较的任何类型值 |
[编辑]返回值
指向所需元素的迭代器。若找不到这种元素,则返回尾后(见 end())迭代器。
[编辑]复杂度
与容器大小成对数。
注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_generic_associative_lookup | 201304L | (C++14) | 关联容器中的异质比较查找; 重载 (3,4) |
[编辑]示例
运行此代码
#include <iostream>#include <set> struct LightKey {int x;}; struct FatKey {int x;int data[1000];// 大型数据块}; // 如上详述,容器必须使用 std::less<>(或其他透明比较器)以访问这些重载。// 这包括标准重载,例如在 std::string 与 std::string_view 之间所用的比较。bool operator<(const FatKey& fk, const LightKey& lk){return fk.x< lk.x;}bool operator<(const LightKey& lk, const FatKey& fk){return lk.x< fk.x;}bool operator<(const FatKey& fk1, const FatKey& fk2){return fk1.x< fk2.x;} int main(){// 简单比较演示。std::set<int> example{1, 2, 3, 4}; if(auto search = example.find(2); search != example.end())std::cout<<"找到了 "<<(*search)<<'\n';elsestd::cout<<"未找到\n"; // 透明比较演示。std::set<FatKey, std::less<>> example2 ={{1, {}}, {2, {}}, {3, {}}, {4, {}}}; LightKey lk ={2};if(auto search = example2.find(lk); search != example2.end())std::cout<<"找到了 "<< search->x <<'\n';elsestd::cout<<"未找到\n";}
输出:
找到了 2 找到了 2
[编辑]参阅
返回匹配特定键的元素数量 (公开成员函数) | |
返回匹配特定键的元素范围 (公开成员函数) |