【问题标题】:Adding a new instance of an array to a vector将数组的新实例添加到向量
【发布时间】: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&lt;float, 3&gt;*) 而不仅仅是数组 (array&lt;float, 3&gt;)?
  • 除此之外,如果你做那个改变,你的整个函数可以变成pinkys.insert(pinkys.end(), pinkys.size(), monster1);
  • 您不能在使用基于范围的 for 循环迭代的容器中添加或删除对象。它使循环内部使用的迭代器无效。
  • 感谢大家的 cmets,除非我将它们指向以前的参考资料,否则某些行为不起作用。我让它工作了。我的更改将很快合并到我的主分支中:my repo.

标签: c++ arrays vector reference instance


【解决方案1】:

正如评论中提到的,您不能将元素插入到您正在使用基于范围的 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&lt;monster&gt;。对于共享所有权,您应该使用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{} );
     }       
}

【讨论】:

  • 感谢您的回答!我理解从迭代每个怪物到迭代大小的变化。如果我没有“访问”怪物而是一个 int,它可能对性能也有帮助。作为对您使用struct 的回应,这是否与执行using Monster = array&lt;float, 3&gt; 之类的操作相同?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多