I'm new to using vectors and am a little bit confused using them. I've written some code and I added some question in the comments. In addition to the questions in my comments, why do we need allocation by using reserve()? If we allocate, we will use won't we? If we need to allocate, is resize() more useful than reserve()? I'm really stuck.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a_vector( 10 );
// equal vector<int> a_vector( 10,0 ); ?
cout << "value of vector first " << a_vector.at(0) << endl; //LEGAL
// cout << a_vector.at(10); // ILLEGAL
cout << "vector size " << a_vector.size() << endl;
a_vector.push_back( 100 );
cout << "value of vector at ten " << a_vector.at(10) << endl; //LEGAL
cout << "vector size " << a_vector.size() << endl;
a_vector.pop_back();
cout << "vector size " << a_vector.size() << endl;
a_vector.resize( 12 );
// also does it mean a_vector[10] = 0; and a_vector[11] = 0;?
cout << "vector size " << a_vector.size() << endl;
cout << "value of vector at ten " << a_vector.at(10) << endl; //LEGAL
cout << "value eleventh " << a_vector.at(11) << endl; //LEGAL
a_vector.pop_back();
a_vector.pop_back();
cout << "vector size " << a_vector.size() << endl;
for (int i = 0; i < 2; i++)
{
//doesn't it same as a_vector.resize( 12 ); now ?
//so why do we need resize(); ?
//also do I need reserve() for using push_back() like this ?
a_vector.push_back(0);
}
cout << "vector size " << a_vector.size() << endl;
a_vector.pop_back();
a_vector.pop_back();
cout << "vector size " << a_vector.size() << endl;
return 0;
}