#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> grades; //declaration of vector
int grade, total;
double average;
total = 0;
for(int i=1; i<=5; ++i) //Taking the input from user
{
cout << "Enter a grade: ";
cin >> grade;
grades.push_back(grade);
}
for(int i = 0; i < grades.size(); ++i)
{
//cout << grades[i] << " ";
total += grades[i];
}
average = total / grades.size();
cout << "the average is " << average << endl;
return 0;
}
OUTPUT:
A vector<int> (meaning 'a vector of ints') in much the same way as you would use an ordinary C array, except that vector eliminates the chore of managing dynamic memory allocation by hand.
vector<int> v(3); // Declare a vector (of size 3 initially) of ints
v[0] = 7;
v[1] = v[0] + 3;
v[2] = v[0] + v[1]; // v[0] == 7, v[1] == 10, v[2] == 17
v.push_back(13); // add another element - the vector has to expand
Note the use of the push_back function - adding elements this way will make the container expand.
Remember that:
1. vector elements can move! insert, for instance, changes its 1st argument.
2. vector doesn't have arithmetic operations: valarray (which is described
later) does. p.51
3. vector doesn't have range-checking by default.