向量将所有负值转换为零

2021-12-21 00:00:00 data-structures vector c++

我制作了一个恒定大小的向量来存储负值,然后打印出我得到的所有值都是零.我只想知道为什么它不存储负值.

I made a vector of constant size to store negative values, and then printing the values all I got was zeroes. I just want to know why it is not storing negative values.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v(5);
    v.push_back(-1);
    v.push_back(-2);
    v.push_back(-3);
    v.push_back(-4);
    v.push_back(-5);

    for (int i=0; i<5; i++)
       std::cout << v[i] << " ";  // All I got was zeroes
}

推荐答案

那是因为 push_back 将 new 元素放在向量的末尾.

That's because push_back puts new elements onto the end of the vector.

运行i9可以看到效果:负数会占用v[5]v[9].

You can see the effect by running i to 9: the negative numbers will occupy v[5] to v[9].

写作

std::vector<int> v{-1, -2, -3, -4, -5};

相反,这是一个特别优雅的修复.

instead is a particularly elegant fix.

相关文章