unordered_set:find 条件查找 包含lambda表达式
时间: 2023-08-06 11:12:08 浏览: 56
unordered_set 的 find() 函数可以用于查找指定元素。如果元素存在,则返回该元素的迭代器;如果不存在,则返回 end()。
可以使用 lambda 表达式作为 find() 函数的参数,以实现条件查找。
例如,假设你有一个 unordered_set<string>,你想查找其中一个长度为 5 且以字母 'a' 开头的字符串:
```c++
#include <iostream>
#include <unordered_set>
#include <string>
int main()
{
std::unordered_set<std::string> myset = {"apple", "banana", "cherry", "date", "elderberry"};
auto it = myset.find([](const std::string& s) { return s.length() == 5 && s[0] == 'a'; });
if (it != myset.end()) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
上面的代码使用 lambda 表达式作为 find() 函数的参数,该 lambda 表达式接受一个 std::string 类型的参数 s,返回值为 bool 类型。如果 s 的长度为 5 且以字母 'a' 开头,则返回 true,否则返回 false。
请注意,lambda 表达式不是 unordered_set 的成员函数,而是作为参数传递给 find() 函数的。