c++ - 复合数据结构和摆弄指针

标签 c++ pointers vector data-structures stl

我正在尝试创建一个由四叉树和一个简单的 STL vector 组成的复合数据结构类,因为我希望能够跨时间范围访问数据(即保持插入对象的顺序)。我最初的实现是维护一个 MyObject 的 STL vector 和一个 const MyObject * const 四叉树。

不用说,在那之后不久我才意识到,在删除这个复合数据结构的那一刻,无法确保首先删除四叉树和 STL vector (保存基础数据),因此可能存在内存问题可能会发生。

我正在考虑在插入新对象时在堆上创建一个 MyObject 实例,四叉树和 STL vector 基本上都保存指向它的指针(使用 shared_ptr 或什么?)

有更好的建议吗?

编辑:这是我目前的实现。我认为只有 insertretrieve... 函数可能是感兴趣的

头文件:

#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/

相关文章:

c++ - 将指向成员函数的指针转换为指向 C 函数的指针是一种好习惯吗

c++ - 分配另一个 std::vector 的 std::vector 地址

matlab - 使用循环将元素添加到 MATLAB 中的现有向量

c++ - std::set - 类似于我的容器中的函数对象支持

c++ - 非复制构造函数干扰静态方法的返回

c - C 中的意外输出(树的遍历)

c++ - 有没有办法拥有一个 bitbucket 指针/C++)

vector 和字符串的 C++ 段错误

c++ - 在编译时对算术 `std::array` 的 `value_type` 进行零初始化会导致缺少构造函数注释

c++ - 为给定的整数递增单个数字 (msb)