ksl*_*ksl 8 c++ stdmap shared-ptr c++11 list-initialization
我有以下shared_ptr内容map:
std::shared_ptr<std::map<double, std::string>>
Run Code Online (Sandbox Code Playgroud)
我想用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);
Run Code Online (Sandbox Code Playgroud)
但是在使用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
Run Code Online (Sandbox Code Playgroud)
我已经尝试了第一个参数(1000.0)的其他变体而没有成功.
有人可以帮忙吗?
std::map 有一个初始化列表构造函数:
map (initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
Run Code Online (Sandbox Code Playgroud)
我们可以很容易地使用这个构造函数创建一个地图:
std::map<double,std::string> m1{{1000.0, s1}};
Run Code Online (Sandbox Code Playgroud)
要使用它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}});
Run Code Online (Sandbox Code Playgroud)
那看起来很笨拙; 但如果你经常需要这个,你可以用别名来整理它:
#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}});
Run Code Online (Sandbox Code Playgroud)
您可能更喜欢定义模板函数来包装调用:
#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}});
Run Code Online (Sandbox Code Playgroud)