Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          vectors/vector-1-modern-compilable.cc - A variant of the simple vector example - executable.Lecture 3 - slide 14 : 27
Program 3

// Compilable and executable variant of program form above.

#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(static_cast<double>(i));

  // Mutation of a EXISTNG ELEMENT.
  a.at(0) = 2.2;

  // Sum up the elements - with iterators - auto:
  sum = 0.0;
  for (auto iter = a.begin();
       iter != a.end();
       iter++){
    sum += *iter;
  }
  cout << "Sum = " << sum << endl;  // 16.2

  // Sum up the elements - with range for:
  sum = 0.0;
  for (auto el: a)
    sum += el;
  cout << "Sum = " << sum << endl;  // 16.2
}