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

Refresh

April 2019

Views

73 time

1

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;
cin>>v[i]

The program returned segmentation fault. Please help me out.

1 answers

3

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;
    v.push_back(new_val); 
}