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

C++输出值为任意类型的unordered_map对象出现死循环如何解决

问题诱因

你的代码出现无限循环输出的核心原因是无限递归调用,具体触发逻辑如下:

  • 你没有为目标类型std::unordered_map<std::string, std::any>重载<<运算符,反而重载了std::any的<<运算符
  • 你写的std::any的<<运算符实现中,完全没有用到传入的std::any参数,反而硬编码遍历了全局的example哈希表,遍历过程中需要输出每个元素的second值(也就是std::any类型),此时就会再次调用你重载的std::any的<<运算符,形成无限递归,最终导致无限循环输出。
修复方案

修复需要满足三个核心要求:

  • 正确为std::unordered_map<std::string, std::any>类型重载<<运算符,而不是重载std::any的
  • 实现std::any的安全打印逻辑:先判断std::any实际存储的类型,再做类型转换后输出,不能直接输出std::any对象
  • 运算符重载逻辑中必须使用传入的参数,不要硬编码全局变量

修复后的参考代码如下:

#include <iostream>
#include <unordered_map>
#include <any>
#include <typeindex>

// 实现std::any的安全打印逻辑
void print_any(std::ostream& os, const std::any& val) {
    if (val.type() == typeid(char)) {
        os << std::any_cast<char>(val);
    } else if (val.type() == typeid(int)) {
        os << std::any_cast<int>(val);
    } else if (val.type() == typeid(std::string)) {
        os << std::any_cast<std::string>(val);
    }
    // 可根据需要扩展支持更多类型的打印
    else {
        os << "[unsupported type]";
    }
}

// 正确重载unordered_map的<<运算符
std::ostream& operator<<(std::ostream& os, const std::unordered_map<std::string, std::any>& map) {
    for (const auto& item : map) {
        os << "{" << item.first << ": ";
        print_any(os, item.second);
        os << "}\n";
    }
    return os;
}

// 测试用例
std::unordered_map<std::string, std::any> example = {
    {"first", 'A'},
    {"second", 2},
    {"third", 'C'}
};

int main() {
    std::cout << example;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:54:02