模式"allocate memory or use existing data"

Pattern "allocate memory or use existing data"

本文关键字:existing data use memory allocate 模式 or      更新时间:2023-10-16

I have field
std::map<std::string, std::map<unsigned int, float>> widths;

我根据运行时标准将数据从另一个地图复制到宽度[键]或将自定义数据插入宽度[键]。但是,复制速度太慢。 我将使用指向 std::map

所以你想根据一些条件引用另一个容器中的std::map<unsigned int, float>

在这种情况下,您需要一个指针映射,例如:std::map<std::string, std::map<unsigned int, float>*>.这样,您将能够执行以下操作:

if(criteria)
widths[key] = &targetMap;

使用std::map对内容进行排序然后迭代并不是一个坏主意,但当然确实取决于真实的上下文。通过推测,我们只能说这是有史以来最好的方法,而永远不要使用其他方法,这是没有意义的

创建以下包装器:

class Widths
{
public:
Widths() : widths(new std::map<unsigned int, float>), to_be_deleted(true)
{
}
Widths(const std::map<unsigned int, float> *arg) noexcept : widths(const_cast<std::map<unsigned int, float>*>(arg)),
to_be_deleted(false)
{
}
~Widths() noexcept
{
if (to_be_deleted) delete widths;
}
Widths(Widths &&arg) : widths(arg.widths), to_be_deleted(arg.to_be_deleted)
{
arg.widths = nullptr;
arg.to_be_deleted = false;
}
Widths(const Widths &arg) = delete;
Widths& operator=(const Widths &arg) = delete;
const std::map<unsigned int, float>* operator->() const
{
return widths;
}
std::map<unsigned int, float>* operator->()
{
return widths;
}
private:
std::map<unsigned int, float> *widths;
bool to_be_deleted;
};

std::map<std::string, std::map<unsigned int, float>> widths;更改为std::map<std::string, Widths> widths;