如何在堆上分配地图 CONTAINER?

问题描述

基本上我有这个地图容器:

map <int,double> r_t_plus_1;

我知道 r_t_plus_1 在堆栈上,它的元素进入动态分配。 我想知道我是否可以通过分配器属性将容器放在堆上,或者有没有更好的方法

解决方法

当然,只需使用 newmake_unique() 在堆上分配它,并将其存储在智能指针中:

auto r_t_plus_1 = std::make_unique<std::map<int,double>>();

如果需要共享指针,也可以使用 make_shared。