Home > Software design >  How to read data from a Vector
How to read data from a Vector

Time:12-03

How can I use the following vector to read true/false from using a while or for loop. With this implemtation of the loop I get an error for the oprator !=

no operator "!=" matches these operands

vector<bool> Verification;

Verification.push_back(true);
Verification.push_back(false);
Verification.push_back(true);
Verification.push_back(false);
Verification.push_back(true);

for (int it = Verification.begin(); it != Verification.end(); it  ) {   
                    if (it==true) cout<<"true";
                    else if (it == false) cout<<"false";
}

CodePudding user response:

You are declaring it as the wrong type. The result of Verification.begin() is a std::vector<bool>::iterator. But you don't need to specify that.

Use a range-for loop instead

for (bool b : Verification) 
{
    std::cout << std::boolalpha << b;
}

CodePudding user response:

There are various ways to iterate over an std::vector

  1. Using iterator

Long example:

for( std::vector<bool>::iterator it = v.begin(); it != v.end();   it ) std::cout << *it;

or the same but shorter:

for( auto it = v.begin(); it != v.end();   it ) std::cout << *it;
  1. Using index

Here:

for( unsigned int i = 0; i != v.size();   i ) std::cout << v[i];
  1. Range loop

Here:

for( bool b : v ) std::cout << b;

(there are some more but we will omit them for clarity)

Looks like you mixed 1 and 2 hense you have compilation errors. Choose one.

CodePudding user response:

The problem is that Verification.begin() gives you an iterator while it is an int.

To solve this you could modify your for loop to:

for (std::vector<bool>::iterator it = Verification.begin(); it != Verification.end(); it  ) {   
                    if (*it==true) cout<<"true";
                    else if (*it == false) cout<<"false";
}

Note *it means we're dereferencing the iterator it and then comparing the result.

Also you don't need the else if because you can just use else.

Alternative solution

You can also use a range-base for loop as shown below:


for (bool element : Verification) 
{
    std::cout << std::boolalpha << element;
}
  •  Tags:  
  • c
  • Related