【问题标题】:std::vector isn't push_back values into my vector? c++std::vector 不是 push_back 值到我的向量中吗? C++
【发布时间】:2020-02-19 09:02:30
【问题描述】:

这是我的代码。

std::vector<int> x;
std::vector<int> y;

void vector_pile()
{
    if (x.size() > 0 && y.size() > 0)
    {
        // clear the x & y movement vectors so we can update it to the current movement vector
        x.clear();
        y.clear();
    }

    // set vector size
    x.resize(WeaponBulletCount());
    y.resize(WeaponBulletCount());

    // updates pattern to move vector to reduce strain on program calculations
    if (WeaponBulletCount() > 0) {
        for (int i = 0; i <= WeaponBulletCount(); i++)
        {           
            x.push_back(i);
            y.push_back(i);

            std::cout << "x: " << x[i] << std::endl;
            std::cout << "y: " << y[i] << std::endl;
        }
    }   
    Sleep(1000);
}

函数WeaponBulletCount();返回值30。这个函数的主要原因是有一个向量可以在变量发生变化时改变,从而减少重复计算的次数。

【问题讨论】:

  • 您将reserveresize 混淆了。
  • 您是否尝试预先分配具有大小的向量,然后将值直接分配到现有索引中?我不明白你问了什么..
  • 旁白:您可以将 x 简化为 x.resize(WeaponBulletCount()); std::iota(x.begin(), x.end(), 0);
  • for 循环中的条件语句看起来像一个非一错误。应该是i &lt; WeaponBulletCount()

标签: c++ vector std


【解决方案1】:

push_back 方法在容器末尾添加新元素(标准组件库中的大多数容器都是典型的)。您在每个容器中创建了 30 个元素,然后在循环中添加了 30 个元素。 x[i] 不是您添加的元素,您正在打印由 resize 创建的值。

你必须使用reserve 来改变向量的容量(也是一种刻板的方法)。

【讨论】:

  • 如果WeaponBulletCount返回30,则循环中会添加31个元素。
  • @1201 哦,是的。他也是从零开始,条件是平等。这是另一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 2021-06-02
  • 2014-05-27
  • 1970-01-01
  • 2015-08-23
相关资源
最近更新 更多