vectors/vector-1.cc - A simple vector example - similar to first array program. | Lecture 3 - slide 14 : 27 Program 1 |
// Similar to array-1.c discussed earlier. #include <iostream> #include <string> #include <vector> // Using declarations: using std::string; using std::vector; using std::cout; using std::endl; int main(){ // Vector construction: vector<double> a; // An empty vector of element type double double sum; // Adding elements to the back end: for (vector<double>::size_type i = 1; i <= 5; i++) a.push_back(i); // Mutation of an EXISTNG ELEMENT: a[1] = 2.2; // Sum up the elements - in a simple for-loop: sum = 0.0; for (int i = 0; i < a.size(); i++){ sum += a[i]; } cout << "Sum = " << sum << endl; // 15.2 // Sum up the elements - with iterators: sum = 0.0; for (vector<double>::iterator iter = a.begin(); iter != a.end(); iter++){ sum += *iter; } cout << "Sum = " << sum << endl; // 15.2 }