在 C++ 的 STL 库中,'std::map' 的 'find' 函数返回一个迭代器,指向找到的元素。如果找到了元素,则返回指向该元素的迭代器;如果没有找到元素,则返回指向 'std::map' 的末尾的迭代器(即 'map.end()')。

以下是一个示例代码,展示了 'std::map' 的 'find' 函数的使用:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;

    myMap.insert(std::pair<int, std::string>(1, 'One'));
    myMap.insert(std::pair<int, std::string>(2, 'Two'));
    myMap.insert(std::pair<int, std::string>(3, 'Three'));

    // 使用 find 查找键为 2 的元素
    std::map<int, std::string>::iterator it = myMap.find(2);

    if (it != myMap.end()) {
        std::cout << 'Element found: ' << it->second << std::endl;
    } else {
        std::cout << 'Element not found' << std::endl;
    }

    return 0;
}

在上面的示例中,'myMap.find(2)' 返回一个迭代器,指向键为 '2' 的元素。如果找到了该元素,则输出 'Element found: Two';否则,输出 'Element not found'。


原文地址: https://www.cveoy.top/t/topic/p8gF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录