Reputation: 164
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";
}
Upvotes: 0
Views: 351
Reputation: 44238
There are various ways to iterate over an std::vector
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;
Here:
for( unsigned int i = 0; i != v.size(); ++i ) std::cout << v[i];
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.
Upvotes: 2
Reputation: 1
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
.
You can also use a range-base for loop as shown below:
for (bool element : Verification)
{
std::cout << std::boolalpha << element;
}
Upvotes: 1