0

I'm in the process of learning c++. I've come across an assignment about temperatures I don't understand. Could you guys clarify some things for me?

Here's the code

// compute mean and median temperatures
int main()
{
vector<double> temps;              // temperatures
for (double temp; cin>>temp; )     // read into temp
temps.push_back(temp);              // put temp into vector

**// compute mean temperature:
double sum = 0;
for (int x : temps) sum += x;
cout << "Average temperature: " << sum/temps.size() << '\n';**

// compute median temperature:
sort(temps);                     // sort temperatures
cout << "Median temperature: " <<  temps[temps.size()/2] << '\n';
}

Now the second block (//compute mean temperature) is the stuff I cannot follow.

First off, a for-statement is used with a single argument. Won't this mean that there is just an initial expression and no condition?

I also don't think I have a firm understanding of int X : temps int X isn't defined anywhere else in this bit of code. Won't it cause an error as it has no value assigned to it? Let's say it has a value of 1; what does it do/what does it check? Does it check how many times X fits in vector temps? Why not do this then:

int sum_of_measurements = 0;                //value of all measurements
for (int y = 0; y <= temps.size(); ++y){  
sum_of_measurements = sum_of_measurements + temps[y];      // add value of measurement to the total for each measurement
}
double mean = sum_of_measurements/temps.size();
cout << mean <<'\n';
//rest of code

What's this identifier called so I can learn more about it (the : in int X : temps)

Thanks :)

  • 4
    It appears your first question is about the [Range-based for loop](https://en.cppreference.com/w/cpp/language/range-for) Go ahead and bookmark the site. If you are learning C++ -- it's all there. – David C. Rankin Jun 28 '18 at 01:32
  • this form of loop is in modern C++ (some loop is in C# and Java). Ma be based on keyword 'foreach', mag be with word 'for', but has educational name 'for each' – Jacek Cz Jun 28 '18 at 01:43
  • If you're learning C++, your course material should have covered the basic C++ constructs including loops. Might be wise to review those. I expect a course which includes a range-based for loop in an assignment to also explain that `for` loop in the main text. – MSalters Jun 28 '18 at 08:11

1 Answers1

1

That's the range-based for loop, introduced in C++11.

A statement like:

for (int someVal: someCollection)

will iterate over someCollection with someVal being set to each item within the collection (one per iteration).

In your specific case (after changing the type of x to one more suitable), the snippet:

double sum = 0;
for (double x : temps)
    sum += x;

is functionally equivalent to:

double sum = 0;
for (int i = 0; i < temps.size(); ++i)
    sum += temps[i];
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953