[英]Segmentation fault in C++ adding item to a vector
Lately I have set myself to learn C++, and while working on a bigger project, I have tried to use 'vectors'.最近我开始学习 C++,在做一个更大的项目时,我尝试使用“向量”。 But every-time I try passing it a value, it exits with a segmentation fault.
但是每次我尝试向它传递一个值时,它都会以分段错误退出。
Here is my terminal output:这是我的终端 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 %
The segfault is because of out of bound access.段错误是因为越界访问。 you need to set the size in the ctor
您需要在 ctor 中设置大小
vector<int> test(1);
or push_back:或推回:
vector<int> test;
test.push_back(0);
Size it vector<int> test = {0,1,2,3,4};
大小
vector<int> test = {0,1,2,3,4};
or vector<int> test(5)
或
vector<int> test(5)
But you might want to use push_back in this situation但是在这种情况下你可能想使用 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;
}
Basically adds an item at the end.基本上在最后添加一个项目。
Can also use maps with the keys be ints if you want to be able to just [] it or leave in spaces (which from what i saw is what your trying to do)如果您希望能够 [] 它或留在空格中,也可以使用键为整数的地图(据我所见,您正在尝试这样做)
#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.