c++

C++ map.find怎样与lambda表达式配合

小樊
81
2024-06-13 17:07:44
栏目: 编程语言

在C++中,可以使用lambda表达式作为比较函数来配合std::map::find方法。例如,可以按照自定义的比较规则查找map中的元素。

下面是一个示例代码:

#include <iostream>
#include <map>

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.first;
    });

    if (findResult != myMap.end()) {
        std::cout << "Key found: " << findResult->first << ", Value: " << findResult->second << std::endl;
    } else {
        std::cout << "Key not found" << std::endl;
    }

    return 0;
}

在上面的代码中,lambda表达式[](const int& a, const std::pair<const int, std::string>& b) { return a < b.first; }用于指定查找规则,即查找键值小于2的元素。

执行以上程序将输出:

Key found: 1, Value: one

这说明在map中找到了键值小于2的元素。

0
看了该问题的人还看了