参考下面的MWE,我有一个包含Point和Cell的Mesh,现在我用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;
}发布于 2016-09-05 18:43:34
我建议你存储其他向量的索引,而不是指针。它们在复制后或向量重新分配后备内存时仍然有效。
我在我的一个项目中做了类似的事情,因为额外的间接性,我有点担心性能。事实证明它甚至比指针更快!可能是因为我用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();
}
}
}请注意,这是脆弱的代码。如果结构中的某些内容发生了变化,而此方法没有相应地更新,则会导致丑陋的bug。
https://stackoverflow.com/questions/39328475
复制相似问题