gpt4 book ai didi

c++ - 使用 braced-init 初始化 std::shared_ptr>

转载 作者:可可西里 更新时间:2023-11-01 17:56:39 27 4
gpt4 key购买 nike

我有以下 shared_ptrmap:

std::shared_ptr<std::map<double, std::string>>

我想使用 braced-init 来初始化它。可能吗?

我试过:

std::string s1("temp");
std::shared_ptr<std::map<double, std::string>> foo = std::make_shared<std::map<double, std::string>>(1000.0, s1);

但是在使用 Xcode 6.3 编译时出现以下错误:

/usr/include/c++/v1/map:853:14: Candidate constructor not viable: no known conversion from 'double' to 'const key_compare' (aka 'const std::__1::less<double>') for 1st argument

我尝试了第一个参数 (1000.0) 的其他变体,但没有成功。

有人能帮忙吗?

最佳答案

std::map 有一个初始化列表构造函数:

map (initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());

我们可以很容易地使用这个构造函数创建一个 map :

std::map<double,std::string> m1{{1000.0, s1}};

要在 make_shared 中使用它,我们需要指定我们提供的 initializer_list 的实例化:

auto foo = std::make_shared<std::map<double,std::string>>
(std::initializer_list<std::map<double,std::string>::value_type>{{1000.0, s1}});

那看起来真的很笨拙;但是如果你经常需要这个,你可以用别名来整理它:

#include <string>
#include <map>
#include <memory>

std::string s1{"temp"};

using map_ds = std::map<double,std::string>;
using il_ds = std::initializer_list<map_ds::value_type>;

auto foo = std::make_shared<map_ds>(il_ds{{1000.0, s1}});

您可能更喜欢定义一个模板函数来包装调用:

#include <string>
#include <map>
#include <memory>

template<class Key, class T>
std::shared_ptr<std::map<Key,T>>
make_shared_map(std::initializer_list<typename std::map<Key,T>::value_type> il)
{
return std::make_shared<std::map<Key,T>>(il);
}

std::string s1{"temp"};
auto foo = make_shared_map<double,std::string>({{1000, s1}});

关于c++ - 使用 braced-init 初始化 std::shared_ptr<std::map<>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445642/

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