这是我上一个问题的延续:嵌套向量<浮动>以及参考操作。
我得到了循环和所有工作,但我正在尝试将数组的新实例添加到总向量中。
以下是我的意思的一个例子:
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
的引用,从而影响其行为。
正如注释中所提到的,您不能将元素插入到使用基于范围的for循环迭代的容器中。这是因为基于范围的for循环在到达pinkys.end()
时停止,但一旦调用pinkys.push_back()
,迭代器就会失效。首先不清楚为什么要迭代pinkys
。循环体中没有使用monster
(向量中元素的副本(。
循环的全部目的似乎是在容器中已有元素的情况下进行尽可能多的迭代。为此,您不需要迭代pinkys
的元素,但可以执行以下操作:
auto old_size = pinkys.size();
for (size_t i=0; i < old_size; ++i) {
// add elements
}
此外,还不清楚为什么要使用指针向量。必须有人拥有矢量中的怪物。如果不是其他人,那就是矢量。在这种情况下,您应该使用std::vector<monster>
。对于共享所有权,应使用std::shared_ptr
。永远不要使用拥有的原始指针!
不要使用普通数组来表示你可以给出更好名称的东西:
struct monster {
float hitpoints; // or whatever it actually is.
float attack; // notice how this is much clearer
float defense; // than using an array?
};
经过这些修改,方法可能看起来像这样:
void duplicateGhosts() {
auto old_size = pinkys.size();
for (size_t i=0; i < old_size; ++i) {
pinkys.push_back( pinkys[i] );
}
}
根据我假设的方法名称,您希望对矢量元素进行双工。如果你只想添加与以前元素一样多的monster
,那就是
void duplicateGhosts() {
auto old_size = pinkys.size();
for (size_t i=0; i < old_size; ++i) {
pinkys.push_back( monster{} );
}
}