C++ 使用 ++ 运算符增加 map<string, int>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5616421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:32:15  来源:igfitidea点击:

increment map<string, int> using ++ operator

c++mapoperators

提问by Edoz

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)

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

这样如果我的地图已经有“单词”作为键,它就会增加它,否则它会创建新的键并增加它。

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?

这就是我关心的地方:如果我在一个新键上执行 map[word]++(这在读取的第一个单词中是不可避免的),我的程序是否会因为我的 map 中的 int 被单元化而崩溃?如果是这样,告诉我的地图的最有效方法是什么:如果单词已经存在,则对值执行 ++,否则,创建值为 1 的新键?在这里使用带有 'map.find' 的 if 语句似乎是多余的,你怎么看?

Thanks

谢谢

回答by James McNellis

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

我的程序会因为地图中的 int 被单元化而崩溃吗?

No; if the element with key worddoesn't exist, the element will be created and value initialized. A value-initialized inthas a value of 0.

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