溫馨提示×

C++ map.find怎樣與lambda表達式配合

c++
小樊
90
2024-06-13 17:07:44
欄目: 編程語言

在C++中,可以使用lambda表達式作為比較函數(shù)來配合std::map::find方法。例如,可以按照自定義的比較規(guī)則查找map中的元素。

下面是一個示例代碼:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};

    // 使用lambda表達式作為比較函數(shù)
    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; }用于指定查找規(guī)則,即查找鍵值小于2的元素。

執(zhí)行以上程序?qū)⑤敵觯?/p>

Key found: 1, Value: one

這說明在map中找到了鍵值小于2的元素。

0