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

C++ unordered_map函数输出异常:标题重复打印问题求助

问题分析与修复

你的代码存在一处未定义行为,正是它导致了printMonth函数输出异常(重复打印标题):

错误根源

在main函数的这一行:

cout<<totalSignedUp(employeeInfo)+"\n";

totalSignedUp返回的是int类型(此处值为2),而"\n"是const char*(字符串指针)。C++不允许直接将整数与指针相加,这会触发指针算术运算:把整数值加到指针地址上,得到一个非法的内存地址,cout尝试输出该地址指向的内容时,会产生不可预测的结果(比如乱码、重复输出、程序崩溃等)。

修复方案

把这行代码改成合法的输出方式,两种任选其一:

  1. 分开输出整数和换行符:
cout << totalSignedUp(employeeInfo) << "\n";
  1. 将整数转为字符串后输出:
cout << to_string(totalSignedUp(employeeInfo)) << "\n";

额外优化建议(非必须,但更高效)

  1. 函数参数改用引用传递,避免unordered_map的不必要拷贝:
    以findDate为例,修改为:
    int findDate(const unordered_map<int, string>& employeeInfo, const string& employeeName)
    
    其他接收unordered_map的函数同理,加上const和&。
  2. totalSignedUp函数可以直接返回容器的size(),无需手动计数:
    int totalSignedUp(const unordered_map<int, string>& employeeInfo)
    {
        return employeeInfo.size();
    }
    

修复后完整代码(示例)

#include <iostream>
#include <unordered_map>
#include <vector>
#include <iomanip>
#include <algorithm>

using namespace std;

int findDate(const unordered_map<int, string>& employeeInfo, const string& employeeName)
{
    int answer = -1;
    for(auto item:employeeInfo)
    {
        if(item.second==employeeName)
           answer=item.first;
    }
    return answer;
}

int totalSignedUp(const unordered_map<int, string>& employeeInfo)
{
    return employeeInfo.size();
}

void printMonth(string title, const unordered_map<int, string>& employeeInfo)
{
    cout<<title<<"\n";
    printf("Date    Name of Employee\n");
    for(auto item: employeeInfo)
    {
        cout << item.first << "    " << item.second << endl;
    }
}

int main()
{    
    unordered_map<int, string> employeeInfo;
    employeeInfo[1]="Ben";
    employeeInfo[2]="Erica";
    cout<<findDate(employeeInfo, "Erica")<<"\n";
    cout<<totalSignedUp(employeeInfo)<<"\n";
    printMonth("Volunteers", employeeInfo);
}

修复后程序会正常输出,不会再出现重复打印标题的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:50:22