阅读量:123
在C++中,可以使用lambda表达式作为比较函数来配合std::map::find方法。例如,可以按照自定义的比较规则查找map中的元素。
下面是一个示例代码:
#include
#include
int main() {
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用lambda表达式作为比较函数
auto findResult = myMap.find(2, [](const int& a, const std::pair<const int, std::string>& b) {
return a < b class="hljs-keyword">if (findResult != myMap.end()) {
std::cout << "Key found: " << findResult>first << ", Value: " << findResult>second << std class="hljs-keyword">else {
std::cout << "Key not found" << std class="hljs-keyword">return 0;
}
在上面的代码中,lambda表达式[](const int& a, const std::pair
执行以上程序将输出:
Key found: 1, Value: one
这说明在map中找到了键值小于2的元素。