mardi 15 août 2017

Vectors: Two Lines, Need Explanation

I am having some trouble understanding what a few lines mean in a code. I recently started learning C++ and picked up Bjarne Stroustrup's "Programming: Principles and Practice Using C++." There is a question in chapter 4 that was tripping me up, so I searched for a solution online to reference. Here is the code I ended up using in conjunction with the book:

#include "std_lib_facilities.h"

int main()
{
vector<double> temps;
for (double temp; cin >> temp;)
    temps.push_back(temp);

double sum = 0;
for (double x : temps) sum += x;
cout << "Average Temperature: " << sum / temps.size() << "\n";

if (temps.size() %2==0) {
    sort(temps);
    cout << "Median Temperature: " << (temps[temps.size() / 2 - 1] + temps[temps.size() / 2]) / 2 << "\n"; //line one
} else {
    sort(temps);
    cout << "Median Temperature: " << temps[temps.size() / 2] << "\n"; //line two
}

keep_window_open();
return 0;
}

I commented on the lines that I don't understand. What exactly is happening with these vectors? I understand that "temps.size()" is used to call upon the elements within a vector and that usually the "-1" means to take the last value. However, when I try and think this through in my head, it just doesn't make sense in conjunction to the outputs. Yes, the output is correct in the code, but could someone please help explain those lines to me? I simply don't want to just copy and paste code and not understand it. I need help understanding at a basic level how the code is being outputted correctly. Thanks!

Aucun commentaire:

Enregistrer un commentaire