-8

I'm currently reading "The Programming Principles" book. It has shown me some vector examples, such as this code:

#include    "std_lib_facilities.h"
#include    <iostream>
#include    <string>
#include    <vector>

using namespace std;

int main()
{
    vector <double> temps;

    double temp = 0;
    double sum = 0;
    double high_temp = 0;
    double low_temp = 0;

    while (cin >> temp)
        temps.push_back(temp);

    for (int i = 0; i<temps.size(); ++i)
    {
        if (temps[i] > high_temp) high_temp = temps[i];
        if (temps[i] < low_temp) low_temp = temps[i];
        sum += temps[i];
    }

    cout << "High temperature: " << high_temp << endl;
    cout << "Low temperature: " << low_temp << endl;
    cout << "Average temperature: " << sum / temps.size() << endl;

    return 0;
}

I don't know what it means when it uses temps[i] putting int i = 0 inside of the brackets. So, what does it indicate? I hope I made myself clear.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Does the book say anything about std::vector before giving the example? Have you used arrays? – Beta Jun 10 '19 at 02:58
  • Every C++ book explains how to use the `[]` operator with vectors. If yours doesn't, you need a better C++ book. If you don't understand something that your book says, post the brief excerpt from the book that confuses you, and explain exactly what your question is about it. – Sam Varshavchik Jun 10 '19 at 03:02
  • They do. My problem here is that I don't understand the use of the variable inside of the brackets. – JERRIVEL RODRIGUEZ Jun 10 '19 at 03:11
  • As a general rule, try to google first before posting a question :). http://www.cplusplus.com/reference/vector/vector/operator[]/ – Hemil Jun 10 '19 at 04:16
  • 1
    @Hemil cplusplus.com is generally considered by many to be a terrible reference site. cppreference.com is much better – Remy Lebeau Jun 10 '19 at 05:12
  • That was the first link i got in google. Well, the point is to google first ;P @RemyLebeau – Hemil Jun 10 '19 at 08:02
  • @Hemil Thank you for your incredible answer. – JERRIVEL RODRIGUEZ Jun 10 '19 at 19:19
  • I didn't answer though. But you are welcome @JERRIVELRODRIGUEZ – Hemil Jun 11 '19 at 03:34

1 Answers1

3

temps[i] means that you are trying to access the "i"th element in the vector. So if i=0 then temps[i] means temps[0].

Tom Johnson
  • 1,793
  • 1
  • 13
  • 31