Duplicate / integer use and narrowing data in a range-based loop

I make my way through the principles and practice of Bjarne Stroustrup programming and experience difficulties. I am currently reading Vectors, and have become familiar with range-based loops. Below I have a code that, from my eyes, seems to read double in INT; that I suppose the reasons are narrowing.

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';
    keep_window_open();
    return 0;
}

Having tried this several times with different inputs, I came to the conclusion that it really narrows. I am creating a double vector, not in a for (int x: temps) loop, taking the first element in temp, putting it in x, processing it, and not incrementing to the next element and repeating. Since the element (double) is read at x (integer), causing a narrowing.

: , (, x int x - ), for (int x: temps ) (double x: temps), , (, ). , .

+4
2

, ( 11.6.4 aka [dcl.init.list] of ++, . 7.1). , . , double x ( auto x, auto, , ).

2- . ( - , , ).

+2
  • , for ( ).
  • , ​​ C/++, (floor ).

, ++:

​​ , ( ). , undefined.

0

Source: https://habr.com/ru/post/1695628/


All Articles