简体   繁体   English

C ++错误:调试断言失败

[英]c++ error: debug assertion failed

I am trying to run this program on visual studio 2010 Pro. 我试图在Visual Studio 2010 Pro上运行此程序。 I can compile it successfully but when I run the programm I get The following error: 我可以成功编译它,但是运行程序时出现以下错误:

Debug Assertion Failed! 调试断言失败! Expression: Vector subscript out of range. 表达式:向量下标超出范围。

in this simple programme I am trying to compute the maximum sum of consecutif non nul numbers in a vector of integers. 在这个简单的程序中,我试图计算整数向量中连续的非nul数的最大和。

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;
int somme(vector<int> tab);

int main() {
vector<int> tab;
tab[0] = 2;
tab[1] = 3;
tab[2] = 0;
tab[3] = 0;
tab[4] = 4;
cout <<somme_consecutifs_max(tab) << endl;
return 0;
}

 int somme(vector<int> tab){
int sum(0);
int max(0);
for (int i = 0; i < tab.size(); ++i){
    if(tab[i] != 0) {
        sum += tab[i];
    }
    else{
        if(sum > max){
            max = sum;
        }
        sum = 0;
    }

}
    return max;
}

on the other hand, why do I cannot initialize my vector of int in Visual Studio 2010 in this why: 另一方面,为什么我不能在Visual Studio 2010中初始化我的int向量,原因如下:

vector<int> tab = {1, 2, 0, 0, 3};

When you do this 当你这样做

vector<int> tab;

you initialize a size 0 vector, which you immediately access out of bounds. 您初始化一个大小为0的向量,您可以立即访问该向量。 You need 你需要

vector<int> tab(5);

to make a size-5 vector. 制作5号尺寸的矢量。 Alternatively, you can push elements back into the vector, increasing the size by one each time. 或者,您可以将元素推回到向量中,每次将大小增加一。

vector<int> tab;
tab.push_back(2);
tab.push_back(3);
....

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

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