参考下面的MWE,我有一个Mesh
,其中包含Point
和Cell
s。现在我用METIS将网格划分为两个,并且想要创建两个新网格。考虑到网格中的圆形指针方向,是否有一种简单的方法可以将新网格的点和单元格的指针更新为新地址?
#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;
}
答案 0 :(得分:0)
我建议你将索引存储到其他向量而不是指针。复制后或向量重新分配后备内存时,它们仍然有效。
我在我的一个项目中做了类似的事情,并因为额外的间接性而担心性能。事实证明它比指针更快!可能是因为我用4B整数替换了8B指针并保存在内存负载上。
如果您坚持使用指向std::vector
元素的指针,您可以在复制后重新映射它们:
// 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();
}
}
}
请注意,这是一个脆弱的代码。如果结构中的某些内容发生了变化,并且此方法没有相应更新,则会导致丑陋的错误。