array vs vector
Array
int A[10];
int n = 5;
for (int i=0; i<n; i++) A[i] = i+1;
cout << "array A contains:";
for (int i=0; i<n; i++)
cout << ' ' << A[i];
cout << endl
cout << "sum of A is " << sum(A, n) << endl;
Vector
vector<int> myvector;
for (int i=1; i<=5; i++) myvector.push_back(i);
cout << "myvector contains:"; for (int i=0; i < myvector.size() ; i++) cout << ' ' << myvector[i];
cout << endl;
cout << "myvector contains:";for (vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it) cout << ' ' << *it; cout << '\n';
cout << "sum of myvector is " << sum(myvector) << endl;
Note:
Both array and vector achieve the same functionality.
Two different ways of looping through vector.
Parameters pass to function sum are different. We need to pass the size of array to sum.
Even though we use int as example, it should be obvious that int can easily be replaced with any other object. The only thing it needs to have is the operator << overloading.
Related exercise is in Input N number