Vector converted all negative values to zero(向量将所有负值转换为零)
问题描述
我制作了一个恒定大小的向量来存储负值,然后打印出我得到的所有值都是零.我只想知道为什么它不存储负值.
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.
运行i
到9
可以看到效果:负数会占用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.
这篇关于向量将所有负值转换为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向量将所有负值转换为零


- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01