新的STD :: MAP条目如何仅通过键插入初始化
How are new std::map entries initialized just by key insertion?
我有一个 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()
来初始化新创建的条目的值,该输入有效地评估了0
的unsigned short
。
请参阅std::map::operator[]
文档(强调矿山 1 ):
1)如果键不存在,则插入
>value_type(key, T())
。此功能等效于return insert(std::make_pair(key, T())).first->second;
-key_type
必须满足CopyConstructible
的要求。
-mapped_type
必须满足CopyConstructible
和DefaultConstructible
的要求。
如果执行插入,则映射值是值initialized(默认为类类型,零initializatized,否则否则),返回了对其的引用。
因此,仅写
std::map<MyString,unsigned short> stringsMap;
.......
stringsMap[ currentString ]++;
很好。整个if
块是多余的,不需要。
1)这不是真的,这是@Remy Lebau的重点
- 表示"accepting anything for this template argument" C++概念的通配符
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 如何仅为一个函数添加延迟
- 运算符C++ "delete []"仅删除 2 个前值
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何用参数值调用函数(仅在运行时已知)
- 如何仅使用其中一个维度在 2D 矢量中插入值?
- 数组 X[n] 仅存储名称.编写算法以在数组中插入或删除 ITEM
- 新的STD :: MAP条目如何仅通过键插入初始化
- 为什么将复制构造器称为25次,而插入循环仅迭代10次
- SQLite C++ 程序值仅在第一次插入第二次不插入
- sqlite3带有参数的多个插入物;仅插入一个记录
- 仅使用 QSql 将选定的值插入 SQLite 表
- 当插入第二个监视器时,全屏Direct3D9设备仅以本机分辨率显示
- 批准std容器用于(仅)插入和迭代
- 是否有一种方法可以将全局名称插入名称空间并使其仅从该名称空间可用