MST

星途 面试题库

面试题:C++ 关联容器之 map 的常见操作与数据检索

在 C++ 中,已知有一个 `std::map<int, std::string>` 类型的变量 `myMap`,请实现以下功能:1. 向 `myMap` 中插入至少三个键值对;2. 通过键来检索对应的值并输出;3. 遍历 `myMap` 并输出所有的键值对。
13.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <map>
#include <string>

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

    // 1. 向 myMap 中插入至少三个键值对
    myMap.insert({1, "one"});
    myMap.insert({2, "two"});
    myMap.insert({3, "three"});

    // 2. 通过键来检索对应的值并输出
    int keyToSearch = 2;
    auto it = myMap.find(keyToSearch);
    if (it != myMap.end()) {
        std::cout << "The value for key " << keyToSearch << " is: " << it->second << std::endl;
    } else {
        std::cout << "Key " << keyToSearch << " not found." << std::endl;
    }

    // 3. 遍历 myMap 并输出所有的键值对
    std::cout << "All key - value pairs in myMap:" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << pair.first << " : " << pair.second << std::endl;
    }

    return 0;
}