std::map
有一个初始化列表构造函数:
map (initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
我们可以很容易地使用这个构造函数创建一个地图:
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}});