1

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!

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I should have known that was the case, but I am very new at this.
1

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;
    }
}

1 Comment

Thank you so much! I should have known that was the case, but I am very new at this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.