简体   繁体   中英

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'. But every-time I try passing it a value, it exits with a segmentation fault.

Here is my terminal 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

vector<int> test(1);

or push_back:

vector<int> test;
test.push_back(0);

Size it vector<int> test = {0,1,2,3,4}; or vector<int> test(5)

But you might want to use push_back in this situation

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM