'Why is the vector subscript out of range?

I'm trying to code this really simple addition program for practice.

It takes in a list of inputs and stores it in a vector. Then it grabs each consecutive element out of the vector and sums it up.

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> i;

    int input;
    int sum = 0;
    int y = 0;

    while (std::cin >> input && input != 0000) {
        i.push_back(input);

    }

    for (y; y < sizeof(i); y++) {

        sum = sum + i[y];
    }
    std::cout << sum;
}

However, when I compile and run the program it works fine up until the for loop starts running and then the compiler stops and spits out the message that the vector subscript is out of range?

What did I do wrong?



Solution 1:[1]

If you want to loop through the vector, you need to check how many elements it has using i.size():

for (y; y < i.size(); y++) 
{
    sum = sum + i[y];
}

This is the canonical use case for range-based for-loops:

for(const auto& elem : i)
    sum += elem;

Or better still use the STL algorithms:

#include <numeric>

const auto sum = std::accumulate(i.begin(), i.end(), 0.0);

Using sizeof gives you the compile-time size of the vector, which refers only to the house-keeping stuff like its size, capacity and data pointer, not the data itself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1