user782311
user782311

Reputation: 971

C++ vector: Assert when using vector array index -1?

Essentially, I have code that has a vector of unordered words, a vector2 that stores their priority(and has their position), a vector3 with the priority sorted from highest to lowest.

I want to make a vector 4 with strings that have highest priority first. The bool warning is in the case of repeat priorities.

But every time I run I get an assertion error. I need help.

Here is the original code:

bool warning = true;
vector<string> vector4;

for (int a = 0; a < vector2.size(); a++)
{
    for (int q = 0 ; q < vector2.size(); q++)
    {
    if (warning && vector2[a] == vector3[a-1] && a>0)
            {
                   warning = false;
            }
     if (warning && vector2[q] == vector3[a])
             {
                     vector4.push_back(vector1[q]);
             }
       warning = true;
    }

}

Here is the code after fixing it using the answers given below:

bool warning = true;
vector<string> vector4;

for (int a = 0; a < vector2.size(); a++)
{
    for (int q = 0 ; q < vector2.size(); q++)
    {
    if (a > 0 && warning && vector2[a] == vector3[a-1])
            {
                   warning = false;
            }
     if (warning && vector2[q] == vector3[a])
             {
                     vector4.push_back(vector1[q]);
             }
       warning = true;
    }

}

Solved!

Upvotes: 1

Views: 4934

Answers (3)

Elemental
Elemental

Reputation: 7521

It seems to me in the first instance of your loop this statement is hit: if (warning && vector2[a] == vector3[a-1]) when a==0 - Thus you evaluate vector[-1] on the RHS of the ==

Upvotes: 1

Joris
Joris

Reputation: 6306

in your loop you do : vector3[a-1]

in the first iteration a = 0 giving a vector3[-1]

This is what makes it assert.

Upvotes: 2

Xeo
Xeo

Reputation: 131839

warning && vector2[a] == vector3[a-1]

Will give you the assertion on the first loop, because a == 0, so a-1 == -1 which is an invalid index.

Upvotes: 2

Related Questions