内存位置的C ++范围错误?

时间:2013-10-03 14:29:30

标签: c++ memory vector location range

新手在这里。尝试运行这个简短的程序时,我似乎在内存位置得到Range Error。我不知道它意味着什么,而且有点令人沮丧。

int main()
{
int grains_current = 1;
vector <int> previous;
int sum = 0;
int i = 0;

for (int i = 0; i<10; ++i) sum += previous[i];
    previous.push_back(grains_current);

    grains_current = grains_current*2;

    if (sum >= 10)
        cout<<i<<"\t\n\n";

1 个答案:

答案 0 :(得分:3)

sum += previous[i];

此时,向量previous未被赋予任何值,因此您将获得未定义行为以访问此地址超出范围。

更新:我认为您的代码应该是:

for (int i = 0; i < 10; ++i)
{
    previous.push_back(grains_current);
    sum += previous[i];

    grains_current *= 2;

    if (grains_current >= 1000)
        std::cout << sum << "\n\n";
}