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

   2024-10-11 8820
核心提示:在C++中,可以使用lambda表达式作为比较函数来配合std::map::find方法。例如,可以按照自定义的比较规则查找map中的元素。下面是

在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的元素。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号