Range Based For - Out of Range Error

OK, I'm working my way through a Udemy course. The instructor has just covered range based for loops a couple videos back. This is the exercise I am working on at the moment. I am only looking for help on the part where the user select 'M'.

When this choice is made, it throws an 'out of range' error.

Here is my code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <vector>
using namespace std;
int main() {
    
    vector<int> numbers {18, 42, 23};
    
    char selection {0};

    do {
            cout << "P - Print numbers" << endl;
            cout << "A - Add a number" << endl;
            cout << "M - Display mean of the numbers" << endl;
            cout << "S - Display the smallest number" << endl;
            cout << "L - Display the largest number" << endl;
            cout << "Q - Quit" << endl;
    
            cout << "Enter your choice: ";
    
            cin >> selection;
            
            if(selection == 'p' || selection == 'P') {
                for (auto i:numbers) {
                    cout << i << " ";
                }
                cout << endl;
            } else if(selection == 'a' || selection == 'A') {
                int add_num {};
                cout << "Enter number to add: ";
                cin >> add_num;
                numbers.push_back(add_num);
                cout << add_num << " added" << endl;
            } else if(selection == 'm' || selection == 'M') {
                if (numbers.size() == 0) {
                    cout << "Unable to calculate the mean - no data" << endl;
                } else {
                    int total {};
                    for (auto i:numbers) {
                        total = total + numbers.at(i);
                    }
                    cout << total << endl;
                }
            } else if(selection == 's' || selection == 'S') {
                cout << "You selected 'S'" << endl;
            } else if(selection == 'l' || selection == 'L') {
                cout << "You selected 'L'" << endl;
            } else if(selection == 'q' || selection == 'Q') {
                cout << "Goodbye!" << endl;
            } else {
                cout << "Unknown selection - please try again" << endl;
            }
        } while (selection != 'q' && selection != 'Q');
    
    
    cout << endl;
    return 0;
}


NOTE: Yes, I know that it won't give the average yet. I am just trying to total the elements of the vector.

Thanks for your help,
Doug
1
2
3
4
5
int total{0};
for (auto i:numbers)
{
    total = total + i; // <--
}


EDIT: couple of typos
Last edited on
Thank you, againtry.

That did it.
Topic archived. No new replies allowed.