C++ cout 不显示任何内容

C++ cout not displaying anything

什么可以解释为什么 cout 在此代码中不显示任何内容?我知道它与行 v[0] = 1; 有关但我不知道为什么,有人对此有解释吗?

编辑:我也知道改变 v[0] = 1;对于 v.push_back(1);会解决问题。

#include <iostream> 
#include <vector> 

using namespace std; 

int main() 
{ 
    vector<int> v; 
    v[0] = 1; 
    cout << "Hello" << endl; 
    return 0; 
}

你不能做 v[0]=1 因为你还没有说向量 v 有多少个元素。所以它导致 运行 时间错误(崩溃)

将其声明为 vector<int>v(10)(这表示 v 将有 10 个元素) 并使用 v[0]=1

如果您事先不知道矢量大小,请使用 v.push_back(1);

这行代码

v[0] = 1; 

实际上调用了未定义的行为,因为未分配与该地址关联的内存。

你在这一行之前加上例如

v.resize(1);
v[0] = 1; 

确保向量项已分配。


#include <iostream> 
#include <vector> 

using namespace std; 

int main() 
{ 
    vector<int> v; 
    v.resize(1);
    // alternatively 
    // vector<int> v(1);

    // alternatively 
    // v.push_back(0);
    v[0] = 1; 
    cout << "Hello" << endl; 
    return 0; 
}

参见fully working sample