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

// Similar to program above, with various modernizations.
// Compiles, but causes an exception to be thrown at run-time.

#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 NON-EXISTNG ELEMENT: Range error caught here (at run-time) with use of at instead of operator[]
  a.at(5) = 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;  

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