向量将所有负值转换为零 [英] Vector converted all negative values to zero

查看:21
本文介绍了向量将所有负值转换为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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_backnew 元素放在向量的末尾.

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.

这篇关于向量将所有负值转换为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆