增量图< string,int>使用++运算符 [英] increment map<string, int> using ++ operator

查看:121
本文介绍了增量图< string,int>使用++运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张地图来计算文件中字词的出现。
我从文件中读取文字,每次我读一个字,我想这样做:

I have a map to count the occurrence of words in a file. I am reading words from the file, and each time I read a word I want to do this:

map[word]++; //(where map is the name of my map, I'm not using map as a name of course)

这样,如果我的地图已经有word作为键,它会递增它,否则创建新的键并递增它。

so that if the my map already has 'word' as a key, it increments it, otherwise it creates the new key and increments it.

我担心:如果我在一个新的密钥(这是不可避免的在第一个字读取)映射[词] ++,我的程序会崩溃,因为我的地图中的int是单位化的?
如果是这样,什么是告诉我的地图的最有效的方式:如果这个词已经存在,对值进行++,否则,创建值为1的新键?
使用带有'map.find'的if语句似乎不必要的多余,你觉得怎么样?

Here's where I am concerned: if I do map[word]++ on a new key (which is unavoidable in the first word read), will my program crash because the int in my map is unitialized? If so, what's the most efficient way of telling my map: if the word is already there, do ++ on the value, otherwise, create the new key with value = 1? Using an if statement with 'map.find' here seems unnecessarily redundant, what do you think?

感谢

推荐答案


我的程序会崩溃,因为我的地图中的int是单位化的?

will my program crash because the int in my map is unitialized?

否;如果键 word 的元素不存在,则将创建元素并初始化值。值初始化的 int 的值为 0

No; if the element with key word doesn't exist, the element will be created and value initialized. A value-initialized int has a value of 0.

这篇关于增量图< string,int>使用++运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆