我基本上是一个字符一个字符地读取文件,当我遇到一个新的数字时,我会将它作为一个元素等于1的键存储在std::map中。遇到相同的数字的次数越多,我就会递增该键的元素:
if(intMap.count(singleCharacter)){
//keyexist just increment count else
//cout<<"exist"<<endl;
int newValue = intMap.at(singleCharacter) + 1; //grabs the value that already exists and we need to incrmenet it by 1 and store the new value in the map.
std::map<int, int>::iterator it = intMap.find(singleCharacter); //finds the single character and increments it by 1.
if (it != intMap.end())
it->second = newValue; //setting the new increment value into the element
}else{
//doesnt exist and and we need to create it and incrmenet by 1
//cout<<"doesnt exist"<<endl;
intMap.insert(pair<int, int>(singleCharacter,1));
cout<<singleCharacter <<" new made : "<<intMap.at(singleCharacter) <<endl;
}
}
for (auto& p : intMap ) {
cout << p.first<<": "<< p.second <<endl;; // "Karl", "George"
}唯一的问题是,当我试图打印出映射中的所有值时,它会给我随机数字,而我不知道它们是从哪里来的。
这就是我正在读的文件:
An International Standard Book Number (ISBN) is a code of 10 characters, referred to as ISBN-10,
separated by dashes such as 0-7637-0798-8. An ISBN-10 consists of four parts: a group code, a publisher code,
a code that uniquely identifies the book among those published by a particular publisher, and a check character.
The check character is used to validate an ISBN. For the ISBN 0-7637-0798-8, the group code is 0,
which identifies the book as one from an English-speaking country. The publisher code 7637 is for "Jones and Bartlett Publishers我得到的输出是:
48: 8
49: 3
51: 3
54: 3
55: 8
56: 4
57: 2 我应该得到的输出应该是:
1: and the amount of times it was seen 这对任何数字都是一样的。
发布于 2021-02-19 03:25:00
您获得这些“随机”数字是因为您使用的是std::map<int,int>而不是std::map<char,int>。打印出来的是字符符号的ASCII数字代码和它们的计数。
因此,您需要更改映射的类型,或者将键转换回char
for (auto& p : intMap ) {
cout << static_cast<char>(p.first) << ": "<< p.second <<endl;
}注意:std::map::operator[]正是为这种情况设计的,在这种情况下,它会将未命中的值初始化为0,因此您的所有条件都可以替换为:
intMap[singleCharacter]++;详细信息可以在this documentation中找到。
https://stackoverflow.com/questions/66266584
复制相似问题