Reputation: 73
What is wrong with this code , why is it giving runtime error ?
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector < int > a[2];
a[0][0]=1;
a[1][0]=2;
cout << a[0][0];
cout << a[1][0];
return 0;
}
Also please correct it .
Upvotes: 0
Views: 2223
Reputation: 29724
why is it giving runtime error ?
vector < int > a[2];
After this declaration vectors are empty yet. So this is undefined behavior trying to acces their elements. This is the cause of runtime error. You need to initialize them first:
vector < int > a[2];
a[0].push_back(1);
a[1].push_back(2);
Declaration
std::vector<int>(10);
specify that this vector has size of 10.
If you want to specify the size of vector
in container you can do it:
std::vector<int> va[2];
va[0] = std::vector<int>(10);
However this might be better:
va[0].reserve(100); // but this just pre-allocates memory, doesn't initialize
Upvotes: 0
Reputation:
operator[]
provides no bounds checking. If you used at
instead, you would get a nice exception telling you what the problem is. It is undefined behavior to provide an index n
if the container size is not greater than n
.
a[0].at(0) =1;
a[1].at(0) =2;
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Upvotes: 0
Reputation: 16318
Because a is an array of two empty vectors. You are trying to access elements that don't exist.
Upvotes: 3
Reputation: 254431
why is it giving runtime error ?
Because the two vectors are empty, so you can't access their elements using []
.
Also please correct it .
vector < int > a[2];
a[0].push_back(1);
a[1].push_back(2);
Upvotes: 4