首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >复制后更新指针地址

复制后更新指针地址
EN

Stack Overflow用户
提问于 2016-09-05 18:20:05
回答 1查看 48关注 0票数 0

参考下面的MWE,我有一个包含PointCellMesh,现在我用METIS将网格一分为二,想要创建两个新的网格。考虑到网格中的圆形指针方向,有没有一种简单的方法可以将新网格的点和单元的指针更新到新地址?

代码语言:javascript
复制
#include <iostream>
#include <vector>

struct Point;
struct Cell;

struct Mesh
{
    std::vector<Point> point;
    std::vector<Cell> cell;
};

struct Point
{
    Cell* parent_cell;
    int partition;
};

struct Cell
{
    std::vector<Point*> vertex;
    int partition;
};

int main()
{
    Mesh mesh;

    mesh.cell.resize(2); // create two triangles.
    mesh.point.resize(4); // 4 points instead of 6 because two of them will be shared.

    // let vertices know their parent cell.    
    mesh.point[0].parent_cell = &mesh.cell[0];
    mesh.point[1].parent_cell = &mesh.cell[0]; mesh.point[1].parent_cell = &mesh.cell[1];
    mesh.point[2].parent_cell = &mesh.cell[0]; mesh.point[2].parent_cell = &mesh.cell[1];
    mesh.point[3].parent_cell = &mesh.cell[1]; 

    // let cells know their vertices.
    mesh.cell[0].vertex.push_back(&mesh.point[0]);
    mesh.cell[0].vertex.push_back(&mesh.point[1]);
    mesh.cell[0].vertex.push_back(&mesh.point[2]);
    mesh.cell[1].vertex.push_back(&mesh.point[1]);
    mesh.cell[1].vertex.push_back(&mesh.point[2]);
    mesh.cell[1].vertex.push_back(&mesh.point[3]);    

    // partition mesh into two.
    // give partition number to points.
    // all but one of the vertices belong to partition 0.
    mesh.point[0].partition = 0;
    mesh.point[1].partition = 0;
    mesh.point[2].partition = 0;
    mesh.point[3].partition = 1; // only this vertex belongs to partition 1.
    // give partition number to cells.
    mesh.cell[0].partition = 0;
    mesh.cell[1].partition = 1;

    // create two new meshes.
    // filter points and cells according to partition number.
    // but how to update pointers?    

    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2016-09-05 18:43:34

我建议你存储其他向量的索引,而不是指针。它们在复制后或向量重新分配后备内存时仍然有效。

我在我的一个项目中做了类似的事情,因为额外的间接性,我有点担心性能。事实证明它甚至比指针更快!可能是因为我用4B整数替换了8B指针,节省了内存负载。

如果您坚持使用指向std::vector元素的指针,则可以在复制后重新映射它们,如下所示:

代码语言:javascript
复制
// Mesh copy constructor
Mesh::Mesh(const Mesh &other) {
    point = other.point;
    cell = other.cell;

    for(Point &p : point) {
        p.parent_cell = p.parent_cell - other.cell.data() + cell.data();
    }

    for(Cell &c : cell) {
        for(Point* &p : c.vertex) {
            p = p - other.point.data() + point.data();
        }
    }
}

请注意,这是脆弱的代码。如果结构中的某些内容发生了变化,而此方法没有相应地更新,则会导致丑陋的bug。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39328475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档