gpt4 book ai didi

C++ 从内存中删除对象

转载 作者:行者123 更新时间:2023-11-28 00:50:31 25 4
gpt4 key购买 nike

假设我已经分配了一些内存并用一组相同类型的对象填充了它,我们将调用这些组件。

假设这些组件中的一个需要删除,执行此操作的好方法是什么,以便可以测试组件创建的“孔”并通过迭代对象集的循环跳过?

反之亦然,我希望能够测试一个洞,以便在空间中存储新组件。

我正在考虑 menclear 并检查 0...

最佳答案

boost::optional<component>似乎完全符合您的需求。将它们放入您的存储中,无论碰巧是什么。例如,使用 std::vector

// initialize the vector with 100 non-components
std::vector<boost::optional<component>> components(100);

// adding a component at position 15
components[15].reset(component(x,y,z));

// deleting a component at position 82
componetnts[82].reset()

// looping through and checking for existence
for (auto& opt : components)
{
if (opt) // component exists
{
operate_on_component(*opt);
}
else // component does not exist
{
// whatever
}
}

// move components to the front, non-components to the back
std::parition(components.begin(), components.end(),
[](boost::optional<component> const& opt) -> bool { return opt; });

关于C++ 从内存中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14325229/

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