std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
std::map, std::unordered_map - narrowing conversion in initializer list
是错误还是标准允许?
#include <iostream>
#include <map>
#include <unordered_map>
int main() {
std::unordered_map<int,int> mm {{44,44}, {33.3, 54}, {222.2,222.2}};
for(auto& [f,s] :mm) {
std::cout<<f<<" - "<<s<<std::endl;
}
std::map<int,int> m {{44,44}, {33.3, 54}, {222.2,222.2}};
for(auto& [f,s] :m) {
std::cout<<f<<" - "<<s<<std::endl;
}
}
在带有 clang10 和 gcc10 的 wandbox.org 上进行测试。std::set
和std::unordered_set
没有这样的问题.
std::map
和std::unordered_map
的元素类型是std::pair
。问题是std::pair
有一个模板化的构造函数,
template< class U1, class U2 > constexpr pair( U1&& x, U2&& y );
使用
std::forward<U1>(x)
初始化first
,使用second
std::forward<U2>(y)
.
例如,给定{33.3, 54}
,U1
被推导为double
,U2
被推导为int
,注意这是一个完全匹配,并且不需要转换来构造std::pair
,那么也不会发生缩小转换。
另一方面,对于std::set
,给定std::set<int> s {33.3};
,将使用std::set
的构造函数std::initializer_list<int>
,并且std::initializer_list<int>
从{33.3}
初始化,发生窄转换。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map