khfrekek
khfrekek

Reputation: 211

simple for if loop not working correctly

I have a very simple for if loop which takes in an array (a vector of vectors) called data, reads the 0th element of EACH row (i.e. the data[i][0] elements), and outputs the 5th elements of THAT specific row IFF it satisfies the condition that the first element is equal to an integer pid (user defined earlier in the code.) If the row doesn't start with that element, i want it to output nothing.

Here is my code for this loop:

for(int i = 0; i < data.size(); i++)  {
    if(data[i][0] = pid) {
        cout << data[i][5] << endl;
    }
}

However, when I run the program, it outputs the 5th element of EVERY row, not just the ones that start with pid. AKA, c++ seems to be completely ignoring my if statement.

Does anyone have an answer to this?

Thank you in advance!

Upvotes: 1

Views: 73

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

You are using assignment operator = instead of the comparison operator ==

if(data[i][0] = pid) {
             ^^^

As for me I would write these loops the following way

for ( size_t i = 0; i < data.size(); i++ )  
{
    if ( data[i][0] == pid && data[i].size() > 5 ) 
    {
        cout << data[i][5] << endl;
    }
}

Upvotes: 1

m.s.
m.s.

Reputation: 16324

You need to use == instead of = inside the if condition:

if(data[i][0] == pid) 

Otherwise you are just assigning the value of pid to the array element and this will be true if pid is not 0.

Upvotes: 5

Related Questions