You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在抛出runtime error后打印std::map的所有条目?

解决C++查找失败时抛出Runtime Error并打印Map内容的问题

你需要添加<stdexcept>头文件来使用标准库的运行时异常类,同时修改lookup函数的逻辑,在查找失败时先打印提示信息和Map内的所有条目,再抛出异常。

修改后的完整代码

#include <iostream>
#include <string>
#include <map>
#include <stdexcept>  // 新增:用于std::runtime_error

class myClass
{
public:
    static bool storeInMap(const std::string& name, int value)
    {
        if(myMap.find(name) == myMap.end())
        { 
            myMap[name] = value;
            return true;
        }
        return false;
    }

    static void lookup(const std::string& name)
    {
        auto it = myMap.find(name);
        if (it != myMap.end())
        {
            std::cout << "Found " << std::endl;
        }
        else
        {
            std::cout << "Not found " << std::endl;
            std::cout << "Available are:" << std::endl;
            // 遍历Map打印所有键
            for (const auto& pair : myMap)
            {
                std::cout << "\"" << pair.first << "\"" << std::endl;
            }
            // 抛出runtime error
            throw std::runtime_error("Key not found in map");
        }
    }

private:
    static std::map<std::string, int> myMap;
};

std::map<std::string, int> myClass::myMap;

int main()
{
    myClass::storeInMap("one", 1);
    myClass::storeInMap("two", 2);
    myClass::lookup("one");
    try
    {
        myClass::lookup("three");
    }
    catch (const std::runtime_error& e)
    {
        // 可选:打印异常信息,不需要可删除此块
        std::cout << "Error: " << e.what() << std::endl;
    }

    return 0;
}

关键修改说明

  1. 引入必要头文件:添加<stdexcept>以使用std::runtime_error类型抛出标准运行时异常。
  2. 重构查找失败逻辑:
    • 先输出你指定的提示文本;
    • 使用范围for循环遍历静态Map,按照预期格式打印所有键;
    • 最后抛出携带自定义信息的std::runtime_error异常。
  3. 捕获异常:用try-catch块包裹可能抛出异常的调用,避免程序因未捕获异常直接终止(若不需要打印异常信息,可移除catch块,不影响之前的提示和Map内容输出)。

运行后输出将符合预期:

Found 
Not found 
Available are:
"one"
"two"
Error: Key not found in map

内容的提问来源于stack exchange,提问作者user18893035

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:50:33