gpt4 book ai didi

c++ - std::map, std::unordered_map - 初始化列表中的缩小转换

转载 作者:行者123 更新时间:2023-12-01 12:42:45 25 4
gpt4 key购买 nike

它是错误还是标准允许?

#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 .

最佳答案

std::map的元素类型和 std::unordered_map std::pair .问题是std::pair有一个模板化的构造函数,

template< class U1, class U2 >
constexpr pair( U1&& x, U2&& y );

Initializes first with std::forward<U1>(x) and second with std::forward<U2>(y).



例如。给定 {33.3, 54} , U1推导出为 doubleU2推导出为 int ,请注意,这是一个精确匹配,并且不需要转换来使用此构造函数来构造 std::pair ,那么也不会发生收缩转换。

另一方面,对于 std::set , 给定 std::set<int> s {33.3}; , std::set 的构造函数服用 std::initializer_list<int>将被使用,并且 std::initializer_list<int>{33.3} 初始化,发生窄转换。

关于c++ - std::map, std::unordered_map - 初始化列表中的缩小转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59837336/

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