我有一个结构元素数组。我需要从数组中删除一些元素,并存储旧值和新值之间的映射。
。e,填充std::map,它的键是来自数组元素的旧索引,它的值是来自数组的新索引。(因为当值从vector中移除时,它会向左移动)
我将用一个例子来说明我需要什么:
0 1 2 3 4 5 6
arr0 = {a, b, c, d, e, f, g}
0 1 2 3 4 5
arr1 = {a, b, c, e, f, g} //after delete d
map[0]=0 // a
map[1]=1 // b
map[2]=2 // c
map[4]=3 // e
map[5]=4 // f
map[6]=5 // g
帮我实现这个。我有一个数组从结构:
struct HalfEdgeHandle { int64_t index = -1; };
std::vector<HalfEdgeHandle> halfEdges = {};
我需要删除数组中一半的元素[I]。Index == -1
只要我理解了你的问题,这应该是解决方案:
struct HalfEdgeHandle {};
std::vector<HalfEdgeHandle> halfEdges = {};
// Here store your data into the vector
std::map<int, int> map;
std::vector<HalfEdgeHandle> copy;
int j = 0;
for(int i = 0; i < halfEdges.size(); i++)
{
if(halfEdges[i].index != -1)
{
copy.append(halfEdges[i]);
map[i] = j++;
}
}
copy
应为不含index == -1
元素的std::vector
。map
将看起来像您所描述的。
让我指出两件事:
- 考虑将
map
和copy
变量名称更改为在代码中更有意义的内容 - 考虑改变存储以前索引和新索引的方式。我会交换键值对,这样你就有连续的索引了。如果你这样做,你可以使用
std::vector
代替std::map
(我通常倾向于避免使用std::map
,当不是强制性的)。