问题描述
什么可以解释为什么 cout 在这段代码中没有显示任何内容?我知道它与行 v[0] = 1; 有关.但我不知道为什么,有人对此有解释吗?
What may explain why the cout is not displaying anything in this code? I know it's related to the line v[0] = 1; but I can't find out why, does someone have an explanation for it?
我也知道改变 v[0] = 1;对于 v.push_back(1);就能解决问题.
I also know that changing v[0] = 1; for v.push_back(1); would solve the problem.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
v[0] = 1;
cout << "Hello" << endl;
return 0;
}
推荐答案
你不能做 v[0]=1
因为你还没说向量 v
有多少个元素代码> 有.所以它会导致运行时错误(它崩溃)
You cannot do v[0]=1
because you haven't said how many elements the vector v
has. So it causes run time error(it crashes)
将其声明为 vectorv(10)
(这表示 v
将有 10 个元素)并使用 v[0]=1
Declare it as vector<int>v(10)
(this says that v
will have 10 elements)and use v[0]=1
或
如果您事先不知道矢量大小,请使用 v.push_back(1);
If you don't know the vector size beforehand use v.push_back(1);
这篇关于C++ cout 不显示任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!