简体   繁体   English

为什么向量下标超出范围?

[英]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?但是,当我编译并运行程序时,它可以正常工作,直到 for 循环开始运行,然后编译器停止并吐出向量下标超出范围的消息?

What did I do wrong?我做错了什么?

If you want to loop through the vector, you need to check how many elements it has using i.size() :如果你想遍历向量,你需要使用i.size()检查它有多少元素:

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

This is the canonical use case for range-based for-loops:这是基于范围的 for 循环的典型用例:

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

Or better still use the STL algorithms:或者更好的是仍然使用 STL 算法:

#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.使用sizeof可以为您提供向量的编译时大小,它仅指诸如大小、容量和数据指针之类的内务管理内容,而不是数据本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM