如果我没有定义向量大小,程序将崩溃 [英] Program crashes if I don'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> example(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
.
这篇关于如果我没有定义向量大小,程序将崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!