C++ 标准库 - <map>

C++ std::map::find 按键查找。找到则迭代器指向该元素,用 ->second 取值;找不到则等于 end(),不要解引用。

原型

iterator find(const key_type& k);
const_iterator find(const key_type& k) const;

参数

  • k:要查找的键。

返回值

指向匹配元素的迭代器,或 end()。

示例

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> m{{"Ada", 95}};
    auto it = m.find("Ada");
    if (it != m.end()) {
        std::cout << it->second << "\n";
    }
    if (m.find("x") == m.end()) {
        std::cout << "no\n";
    }
    return 0;
}

输出:

95
no

注意事项

只读查找不要用 operator[],它会在键不存在时插入 0。

下一页介绍at:键不存在时抛出异常。