Why I can't input into my std::vector in C++


April 2019


73 time


I'm a newbie in C++. I've just learnt about vector in STL.

However, when I tried to input an integer into my vector:

vector<int> v;

The program returned segmentation fault. Please help me out.

1 answers


Your vector doesn't have any elements in it, so the internal array is null. When you try to read something into it, you're trying to deference a null pointer (resulting in the segfault). Add elements to the vector first:

vector<int> v(100); //Create vector with 100 elements

for(int i = 0; i < 100; i++) {
    cin >> v[i]; 

Alternatively, you could read elements into a local variable, then add them into the vector:

vector<int> v; 
for(int i = 0; i < 100; i++) {
    int new_val;
    cin >> new_val;