2

here's some c++ code.

vector<double> temps;
for (double temp; cin>>temp;) 
temps.push_back(temp); 
double sum = 0;
for (int x : temps) sum += x; //what is this doing? 
cout << "Average temperature:

So the line:

 for (int x : temps) sum += x;

What is it doing? Where is sum's value coming from?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
the
  • 39
  • 1
  • 1
  • 4
  • ill write this as a comment> check out ranged based loop http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html – AndersK Aug 14 '15 at 03:51
  • Are you asking about the `for (int x : temps)` part, or the `sum += x` part? – Raymond Chen Aug 14 '15 at 03:52
  • I'm talking about (for int x: temps) part mostly. I know that sum += x is just another way of typing sum = sum + x – the Aug 14 '15 at 03:57
  • 1
    the, I've removed whole bunch of unrelated text from your post (as noone cares about *your* smartness as long as post contains enough information). Please make sure remaining text clearly specify your problem. – Alexei Levenkov Aug 14 '15 at 03:57
  • I cared... I cared... – the Aug 14 '15 at 04:51
  • Okay, because you asked, "Where is sum's value coming from?" which suggested that you didn't understand what `sum += x;` means. – Raymond Chen Aug 14 '15 at 05:16
  • I don't understand anything, but that isn't your problem. – the Aug 14 '15 at 05:25
  • The previous dupe target was wrong. I've edited the list to point to the correct target. – cigien Nov 06 '20 at 19:49

5 Answers5

4

for(int x : temp) { sum += x; } is defined as being equivalent to:

for ( auto it = begin(temp); it != end(temp); ++it ) 
{ 
    int x = *it;
    sum += x;
}

For a vector, begin(temp) resolves to temp.begin(), and auto resolves to vector::iterator. The new syntax is easier to read and write, obviously.

M.M
  • 138,810
  • 21
  • 208
  • 365
3

It's an enhanced for loop, it's pretty much a nicer way of writing regular for loops, and without the variable used to index arrays. It's the equivalent of:

for (int i = 0; i < temps.size(); i++)
    sum += temps.at(i);
Shadow
  • 3,926
  • 5
  • 20
  • 41
2

This is a C++11 range-based for loop over the contents of the vector temps.

x takes each value in that vector, and the body of the loop (sum += x) increments sum by x for each value. The result is that sum is the sum over all values in the vector.

jacobsa
  • 5,719
  • 1
  • 28
  • 60
1

for (int x : temps) means loop over temps, get every element in x, sum += x; means summarize x to sum. At last you'll get the summing value.

Reference for Range-based for loop

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

x gets its value from the elements in the vector temp.

The loop:

for(int x : temp)

is a c++11 style loop that just runs over (iterates) each element in the vector and copies it into x. Then x can be using within the body of the loop.

sashang
  • 11,704
  • 6
  • 44
  • 58