什么可以解释为什么 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.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;
}
See the 完全工作的样本 http://ideone.com/Vjt2qB.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)