// Similar to program above, with various modernizations. // Compiles, but causes an exception to be thrown at run-time. #include #include #include // Using declarations: using std::string; using std::vector; using std::cout; using std::endl; int main(){ // Vector construction: vector a{}; // An empty vector of element type double double sum; // Adding elements to the back end: for (vector::size_type i = 1; i <= 5; i++) a.push_back(static_cast(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; }