如果我没有定义矢量大小,程序会崩溃
目前正在学习 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
.
相关文章