C++ unordered_map函数输出异常:标题重复打印问题求助
问题分析与修复
你的代码存在一处未定义行为,正是它导致了printMonth函数输出异常(重复打印标题):
错误根源
在main函数的这一行:
cout<<totalSignedUp(employeeInfo)+"\n";
totalSignedUp返回的是int类型(此处值为2),而"\n"是const char*(字符串指针)。C++不允许直接将整数与指针相加,这会触发指针算术运算:把整数值加到指针地址上,得到一个非法的内存地址,cout尝试输出该地址指向的内容时,会产生不可预测的结果(比如乱码、重复输出、程序崩溃等)。
修复方案
把这行代码改成合法的输出方式,两种任选其一:
- 分开输出整数和换行符:
cout << totalSignedUp(employeeInfo) << "\n";
- 将整数转为字符串后输出:
cout << to_string(totalSignedUp(employeeInfo)) << "\n";
额外优化建议(非必须,但更高效)
- 函数参数改用引用传递,避免
unordered_map的不必要拷贝:
以findDate为例,修改为:
其他接收int findDate(const unordered_map<int, string>& employeeInfo, const string& employeeName)unordered_map的函数同理,加上const和&。 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
相关产品推荐
相关产品推荐

