c++ - 找不到我存储到地图中的值
问题描述
我基本上是逐个字符地读取文件,当我遇到一个新数字时,我将它std::map
作为一个元素存储在一个键中,元素等于 1。我遇到相同数字的次数越多,我就会增加该键的元素:
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
这对任何数字都是一样的。
解决方案
你得到那些“随机”数字是因为你使用的是std::map<int,int>
而不是std::map<char,int>
. 您打印的是字符符号的 ASCII 数字代码及其计数。
So, you need to either change the map's type, or cast the keys back to char
:
for (auto& p : intMap ) {
cout << static_cast<char>(p.first) << ": "<< p.second <<endl;
}
Note: std::map::operator[]
is precisely designed for such case, it will initialize missed values with 0 in this case, so all of your conditions can be replaced with:
intMap[singleCharacter]++;
Details can be found in this documentation.
推荐阅读
- ruby-on-rails - Rails - 动态添加更多嵌套属性
- android - 为什么我的电脑中有 2 个 Android SDK 文件夹
- c# - 访问两个解决方案(C#、异步)之间的列表项
- c# - 从运行 .Net 核心的不同容器访问 docker 卷文件
- node.js - 是否有任何其他命令可以自动重新加载网页?
- android - Android + iOS - 从带有指定参数的 WWW 链接安装 + 运行/运行应用程序
- git - 如何通过丢弃所有更改将远程源主分支的所有更改复制到本地的新分支
- reactjs - 反应:未捕获的类型错误:tokenIds.map 不是函数
- linux - pulseaudio:无法初始化 PA contextaudio:无法初始化“pa”音频驱动程序
- android - 操作栏中的 Android 个人资料图片