gpt4 book ai didi

c++ - 新的 std::map 条目如何仅通过键插入来初始化?

转载 作者:行者123 更新时间:2023-11-30 01:38:32 27 4
gpt4 key购买 nike

我有一个 std::vector<MyString>哪些数据不是唯一的。实际上,大多数字符串都是重复的。而且我必须找到唯一的和它们的重复编号。

我使用 map :

std::map<MyString,unsigned short> stringsMap;
.......
if ( stringsMap.find( currentString ) == stringsMap.end() )
{
stringsMap[ currentString ] = 0;
}

stringsMap[ currentString ]++;
........

您是否知道如何在更少的线路上完成它?

可以在一行中完成:stringsMap[ currentString ]++;但是默认情况下,short 具有不确定的值。

最佳答案

It could be done on one row: stringsMap[ currentString ]++; however short has indeterminate value by default.

这不是真的,值在 documentation 中明确定义:

If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

重点是我的。

所以写一个类轮是完全没问题的:

stringsMap[ currentString ]++;

这是常见的做法,甚至在文档中作为示例给出:

// count the number of occurrences of each word
// (the first call to operator[] initialized the counter with zero)
std::map<std::string, size_t> word_map;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
"this", "sentence", "is", "a", "hoax"}) {
++word_map[w];
}

关于c++ - 新的 std::map 条目如何仅通过键插入来初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47660098/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com