我正在尝试创建一个由四叉树和一个简单的 STL vector 组成的复合数据结构类,因为我希望能够跨时间范围访问数据(即保持插入对象的顺序)。我最初的实现是维护一个 MyObject
的 STL vector 和一个 const MyObject * const
四叉树。
不用说,在那之后不久我才意识到,在删除这个复合数据结构的那一刻,无法确保首先删除四叉树和 STL vector (保存基础数据),因此可能存在内存问题可能会发生。
我正在考虑在插入新对象时在堆上创建一个 MyObject
实例,四叉树和 STL vector 基本上都保存指向它的指针(使用 shared_ptr
或什么?)
有更好的建议吗?
编辑:这是我目前的实现。我认为只有 insert
和 retrieve...
函数可能是感兴趣的
头文件:
#include "MapQuadTree.hpp"
typedef cv::Point2d Coordinate_t;
class PointsData
{
private:
const unsigned int mMaxLevels = 10;
const unsigned int mMaxPerLevel;
unsigned int mMaxDataSize;
unsigned int mCurrentIndex;
std::vector<Coordinate_t> mPointsVector;
MapQuadTree mPointsQuadtree;
public:
PointsData(const unsigned int maxDataSize, double mapWidth, double mapHeight);
~PointsData();
Coordinate_t operator[](int index);
Coordinate_t last();
Coordinate_t first();
bool insert(const Coordinate_t& point);
void retrieveNeighboringPoints(const Coordinate_t& point, std::vector<Coordinate_t>& neighbors);
};
源文件:
#include "PointsData.hpp"
PointsData::PointsData(const unsigned int maxDataSize, double mapWidth, double mapHeight)
: mMaxPerLevel(maxDataSize / mMaxLevels), mMaxDataSize(maxDataSize), mPointsVector(maxDataSize), mCurrentIndex(0),
mPointsQuadtree(0, maxDataSize / mMaxLevels, mMaxLevels, Coordinate_t(-1.0*mapWidth/2, -1.0*mapHeight/2), mapWidth, mapHeight)
{
}
PointsData::~PointsData()
{
}
Coordinate_t PointsData::operator[](int index)
{
return mPointsVector[index];
}
Coordinate_t PointsData::last()
{
return mPointsVector.back();
}
Coordinate_t PointsData::first()
{
return mPointsVector.front();
}
bool PointsData::insert(const Coordinate_t& point)
{
if (mCurrentIndex >= mMaxDataSize)
return false;
mPointsVector[mCurrentIndex] = point;
mPointsQuadtree.insert(&mPointsVector[mCurrentIndex]);
mCurrentIndex++;
return true;
}
void PointsData::retrieveNeighboringPoints(const Coordinate_t& point, std::vector<Coordinate_t>& neighbors)
{
std::vector<const Coordinate_t * const> results;
mPointsQuadtree.retrieve(point, results);
neighbors.clear();
for (const Coordinate_t * const elemPtr : results) {
neighbors.push_back(*elemPtr);
}
}
最佳答案
内存管理应该委托(delegate)给你的容器。一个可能的建议应该是在你的 vector 中使用智能指针,如下所示:
std::vector<std::shared_ptr<MyObject>>
如果保存对象的内存将被共享或 std::vector<std::unique_ptr<MyObject>>
如果不共享该内存。
关于c++ - 复合数据结构和摆弄指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27648940/