我正在尝试通过将从文件读取的值插入到C ++映射中来消除存储在文件中的重复项。 输入:
1 1 2 3
以下是逻辑:
do
{
ret = read(fd, (void*)&value, 1);
if(ret != -1 && ret != 0 && value != 10 && value != 32 )
{
insertVal = value - 48;
cout<<"value computed " << insertVal << endl;
if(numArr[insertVal] == 0)
numArr[insertVal] = 100;
}
insertVal = 0;
}while(ret!= 0);
输出:
value computed 1
value computed 1
value computed 2
value computed 3
如果我使用map,则使用数组
逻辑更改为
do
{
ret = read(fd, (void*)&value, 1);
if(ret != -1 && ret != 0 && value != 10 && value != 32 )
{
insertVal = value - 48;
cout<<"value computed " << insertVal << endl;
numberMap.insert(std::pair<int, int>(insertVal, 100));
}
insertVal = 0;
}while(ret!= 0);
输出:
value computed 4200410 value computed 4200449 value computed 4200432 value computed 4200449 value computed 4200410 value computed 4200450 value computed 4200432 value computed 4200451 value computed 4200410
我的问题是,为什么地图插入对垃圾有价值。请帮帮我。
答案 0 :(得分:0)
你过度复杂化了。读入std::map
的简单方法是
std::map<int, int> numberMap;
std::ifstream fd("file_name");
...
for (int value; fd >> value;) {
if (value == 10 || value == 32) continue;
int insertVal = value - 48;
numberMap[insertVal] = 100;
}