Program crashes if I don#39;t define a vector size(如果我没有定义矢量大小,程序会崩溃)
问题描述
目前正在学习 C++,偶然发现了这个问题
Currently learning C++ and stumbled upon this problem
std::vector<int> example;
example[0] = 27;
std::cout << example[0];
这会使程序崩溃,但如果我定义一个大小 std::vector<int>示例(1)
它工作正常.我还注意到,如果我使用 example.push_back(27)
而不是 example[0] = 27
而不定义大小,它也可以正常工作.这背后有什么原因吗?
This crashes the program, but if I define a size std::vector<int> example(1)
it works fine. What I also noticed was that if I use example.push_back(27)
instead of example[0] = 27
without defining the size it also works fine. Is there a reasoning behind this?
推荐答案
一个空向量在内存中没有分配任何元素.
An empty vector has no elements allocated in memory.
您应该使用 example.push_back(27)
而不是尝试下标.push_back()
分配一个新元素,然后将其添加到向量中.一旦将新元素添加到向量中,就可以使用 example[0] = something
重新分配它.
You should use example.push_back(27)
instead of trying to subscript it. push_back()
allocates a new element and then adds it to the vector. Once that new element is added to the vector, it can be reassigned using example[0] = something
.
这篇关于如果我没有定义矢量大小,程序会崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果我没有定义矢量大小,程序会崩溃


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01