新的STD :: MAP条目如何仅通过键插入初始化

How are new std::map entries initialized just by key insertion?

本文关键字:插入 何仅通 初始化 STD MAP 新的      更新时间:2023-10-16

我有一个 std::vector<MyString>,哪个数据不是唯一的。实际上,大多数字符串都重复。我必须找到独特的及其重复号码。

我使用地图:

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

您有想法如何在较少的行上完成?

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

可以在一行上完成:stringsmap [currentstring] ;但是,默认情况下的短距离具有不确定的值。

这不是真的,值的定义很好,如文档中所述:

如果执行了插入,则映射的值是值initialized(默认为类类型的默认值,零启动化,否则否则),返回了对其的引用。

>

强调是我的。

所以写一个衬里是完全可以的:

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];
}

但是,默认情况下,缩短值不确定。

否。对于非现有键,该地图将使用T()来初始化新创建的条目的值,该输入有效地评估了0unsigned short

请参阅std::map::operator[]文档(强调矿山 1 ):

1)如果键不存在,则插入value_type(key, T())。此功能等效于return insert(std::make_pair(key, T())).first->second;
-key_type必须满足CopyConstructible的要求。
-mapped_type必须满足CopyConstructibleDefaultConstructible的要求。
如果执行插入,则映射值是值initialized(默认为类类型,零initializatized,否则否则),返回了对其的引用。

>

因此,仅写

std::map<MyString,unsigned short> stringsMap;
.......
stringsMap[ currentString ]++;

很好。整个if块是多余的,不需要。


1)这不是真的,这是@Remy Lebau的重点