简体   繁体   中英

c++ error: debug assertion failed

I am trying to run this program on 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.

#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:

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. You need

vector<int> tab(5);

to make a size-5 vector. 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);
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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