I am working on a program that uses vectors. So the first thing I did was declare my vector.
std::vector<double> x;
x.reserve(10)
(BTW, is this also considered bad practice? Should I just type std::vector<double> x(10)
?)
Then I proceeded to assign values to the vector, and ask for its size.
for (int i=0; i<10; i++)
{
x[i]=7.1;
}
std::cout<<x.size()<<std::endl;
I didn't know it would return 0
, so after some searching I found out that I needed to use the push_back method instead of the index operator.
for (int i=0; i<10; i++)
{
x.push_back(7.1);
}
std::cout<<x.size()<<std::endl;
And now it returns 10
.
So what I want to know is why the index operator lets me access the value "stored" in vector x
at a given index, but wont change its size. Also, why is this bad practice?