【发布时间】:2021-09-23 17:23:35
【问题描述】:
这是我之前问题的延续:Nested vector<float> and reference manipulation。
我得到了循环并且一切正常,但我正在尝试将新的数组实例添加到总向量中。
这是我的意思的一个例子:
array<float, 3> monster1 = { 10.5, 8.5, 1.0 };
// ...
vector<array<float, 3>*> pinkys = { &monster1};
// ...
void duplicateGhosts() {
int count = 0;
int i = pinkys.size(); // this line and previous avoid overflow
array<float, 3>& temp = monster1; // this gets the same data, but right now it's just a reference
for (auto monster : pinkys) { // for each array of floats in the pinkys vector,
if (count >= i) // if in this instance of duplicateGhosts they've all been pushed back,
break;
pinkys.push_back(&temp); // this is where I want to push_back a new instance of an array
count++;
}
}
使用当前代码,它不是创建新的monster,而是添加对原始monster1 的引用,从而影响其行为。
【问题讨论】:
-
您是否有理由在向量中使用数组指针 (
array<float, 3>*) 而不仅仅是数组 (array<float, 3>)? -
除此之外,如果你做那个改变,你的整个函数可以变成
pinkys.insert(pinkys.end(), pinkys.size(), monster1); -
您不能在使用基于范围的 for 循环迭代的容器中添加或删除对象。它使循环内部使用的迭代器无效。
-
感谢大家的 cmets,除非我将它们指向以前的参考资料,否则某些行为不起作用。我让它工作了。我的更改将很快合并到我的主分支中:my repo.
标签: c++ arrays vector reference instance