Reputation: 123
I cannot seem to find the reason why the contents of my vector components are not supplied using the for loop and cout. Background to the code is that I want to know what happens when you resize a vector that already exists (if made smaller, which components fall away, if larger, which components are added,...)
#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
vector<double> a;
for (int i = 1; i < 10; ++i)
a[i] = 5;
a.resize(15)
for (int i = 1; i < a.size(); ++i)
cout << a[i] << endl;
return 0;
}
Upvotes: 0
Views: 361
Reputation: 311176
The program has undefined behavior because the declared vector is empty and you may not use the subscript operator for an empty vector.
vector<double> a;
for (int i = 1; i < 10; ++i)
a[i] = 5;
Moreover the indices of vectors start from 0.
You could either write
vector<double> a( 10 );
for (int i = 0; i < 10; ++i)
a[i] = 5;
or
vector<double> a;
for ( int i = 0; i < 10; ++i)
a.push_back( 5 );
Or to make the last code snippet more efficien you could write
vector<double> a;
a.reserve( 10 );
for ( int i = 0; i < 10; ++i)
a.push_back( 5 );
Again to output the full content of the vector you should start indices from 0. Or you could use the range based for loop like
for ( const auto &item : a ) std::cout << item << '\';
Upvotes: 2
Reputation: 5148
You did not change the size of the vector. To insert into a vector you can use the push_back
or emplace_back
methods. If you change the insertig code to
for (int i = 1; i < 10; ++i)
a.push_back(i);
or alternatively use the resize
method before you assign
a.resize(10);
for (int i = 1; i < a.size(); ++i)
a[i] = i;
then the print loop should work fine.
Upvotes: 0
Reputation: 1614
You have an out-of-bounds access in your code. You need to resize your vector before filling it. Alternatively you can use push_back
to insert elements.
In either case, it will work as you expect.
Upvotes: 0