[英]Segmentation fault in C++ adding item to a vector
最近我开始学习 C++,在做一个更大的项目时,我尝试使用“向量”。 但是每次我尝试向它传递一个值时,它都会以分段错误退出。
这是我的终端 output:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> test;
cout << "hello world" << endl;
test[0] = 0;
return 0;
}
me@my-MacBook-Pro Desktop % g++ test.cpp -o o && ./o
hello world
zsh: segmentation fault ./o
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> test;
cout << "hello world" << endl;
//test[0] = 0;
return 0;
}
me@my-MacBook-Pro Desktop % g++ test.cpp -o o && ./o
hello world
me@my-MacBook-Pro Desktop %
段错误是因为越界访问。 您需要在 ctor 中设置大小
vector<int> test(1);
或推回:
vector<int> test;
test.push_back(0);
大小vector<int> test = {0,1,2,3,4};
或vector<int> test(5)
但是在这种情况下你可能想使用 push_back
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> test;
cout << "hello world" << endl;
test.push_back(0);
cout << test[0];
return 0;
}
基本上在最后添加一个项目。
如果您希望能够 [] 它或留在空格中,也可以使用键为整数的地图(据我所见,您正在尝试这样做)
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<int, int> test;
cout << "hello world" << endl;
test[0] = 0;
cout << test[0];
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.