将文件中字符键与浮点值存入std::map时遇编译错误求助
问题:将文本文件值存入std::map时触发编译错误
编译错误信息:
error: array used as initializer
1817 | : first(std::forward<_Args1>(std::get<_Indexes1>(__tuple1))...),
使用的函数代码:
fstream DistanceFile; map<char[2], float> odleglosci; void loadkeysdistance() { char temp[2]; string templine = ""; float tempfloat = 0; DistanceFile.open("keys.txt"); while (!DistanceFile.eof()) { getline(disctionary, templine); temp[0] = templine[0]; temp[1] = templine[2]; tempfloat = stof(templine.substr(4, templine.length() - 4)); odleglosci[temp] = tempfloat; } }
文本文件keys.txt内容示例:
A A 0 A B 87.82 A C 51.29 A D 38.10 A E 38.40 A F 57.15 A G 76.20 A H 95.25
解决方案
核心问题是C++的std::map不能直接用数组作为键:数组没有默认的复制构造函数,也无法被std::map要求的比较运算符(<)正确处理,这就是编译错误的根源。
解决步骤:
- 替换键类型:用
std::pair<char, char>代替char[2],pair自带合法的复制和比较逻辑,完全适配std::map的要求。 - 修正变量名错误:代码中
getline(disctionary, templine)里的disctionary是拼写错误,应该改为DistanceFile。 - 修复循环逻辑:
while (!DistanceFile.eof())会导致多读一行空数据,改成把getline放在循环条件里,确保只有成功读取行时才执行循环体。
修改后的代码:
#include <fstream> #include <map> #include <string> #include <utility> // 用于std::pair using namespace std; fstream DistanceFile; map<pair<char, char>, float> odleglosci; void loadkeysdistance() { string templine = ""; float tempfloat = 0; DistanceFile.open("keys.txt"); while (getline(DistanceFile, templine)) { char c1 = templine[0]; char c2 = templine[2]; tempfloat = stof(templine.substr(4)); // substr只传起始位置即可,默认到末尾 odleglosci[{c1, c2}] = tempfloat; } }
内容的提问来源于stack exchange,提问作者Ordex_
相关产品推荐
相关产品推荐

