是窃听器还是斯坦特允许的?
#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;
}
}在wandbox.org上用clang10和gcc10测试它。std::set和std::unordered_set没有这样的问题。
发布于 2020-01-21 09:08:00
std::map和std::unordered_map的元素类型是std::pair。问题是std::pair有一个模板构造函数,
template<类U1,类U2 >U2对(U1& x,U2&y ); 用
std::forward<U1>(x)初始化first,用std::forward<U2>(y)初始化second。
例如,给定{33.3, 54},U1被推导为double,U2被推导为int,注意这是完全匹配的,并且这个构造函数不需要转换来构造std::pair,然后也不会发生收缩转换。
另一方面,对于std::set,给定std::set<int> s {33.3};,将使用std::set获取std::initializer_list<int>的构造函数,并且从{33.3}初始化std::initializer_list<int>,就会发生窄转换。
https://stackoverflow.com/questions/59837336
复制相似问题