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
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01