Daokr23
Daokr23

Reputation: 27

Why does runtime error show when vector is empty?

I have the following code, where I try to find the minimum of a vector if it has more than 0 elements, otherwise return -1.

But, when the vector is empty, I get the following runtime error:

Vector Subscript out of range.

int S = 0;
string s1 = "";
int n;
cin >> n;
int c[10];
string vitamins[10];
vector <int> mask1;
for (int i = 0;i < n;i++)
{
    cin >> c[i];
    cin >> vitamins[i];
}
for (int a = 0;a < (1 << n);a++)
{
    for (int b = 0;b < n;b++)
    {
        if (a & (1 << b))
        {
            s1 += vitamins[b];
            S += c[b];
        }
    }
    if(s1.find('A') != string::npos &&s1.find('B') != string::npos && s1.find('C') != string::npos)
    {
        mask1.push_back(S);
    }
    S = 0;
    s1 = "";
}
int minimum = mask1[0];
int size = mask1.size();
if(mask1.empty())
{
    cout<<-1<<endl;
}
else
{
    for (int m = 1;m < size;m++)
    {
        if (minimum > mask1[m])
        {
            minimum = mask1[m];
        }
    }
    cout << minimum << endl;
}

Upvotes: 0

Views: 370

Answers (1)

Christopher Miller
Christopher Miller

Reputation: 3461

In this line:

int minimum = mask1[0];

You access the first index of mask1 before checking if it is empty. In the case that it is empty (i.e. the size is 0), this would result in undefined behavior.

You should place this declaration after you check if mask1 is empty.

Upvotes: 2

Related Questions