Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find out if all elements in a vector are false or true c++?

Tags:

c++

vector

I was wondering if there was a quick way to find out if all elements in a vector are false or true? Like instead of checking each element using a loop?

like image 602
LoveMeow Avatar asked Nov 12 '14 20:11

LoveMeow


People also ask

How do you check all the elements in vector are equal or not?

A simple solution to check if all elements of a vector are equal is using the std::adjacent_find function. It returns the first occurrence of adjacent elements that satisfies a binary predicate, or end of the range if no such pair is found.

What method can be used to determine the number of elements in a vector?

Use the Vector. size method. It will tell you the number of elements in the vector.

How do you compare elements in vectors?

Comparing two vectors using operator == std::vector provides an equality comparison operator==, it can be used to compare the contents of two vectors. For each element in the vector it will call operator == on the elements for comparisons.


1 Answers

I'd take advantage of the new algorithms for clarity:

// all true
std::all_of(vec.begin(), vec.end(), [](bool v) { return v; });

// all false
std::all_of(vec.begin(), vec.end(), [](bool v) { return !v; });
std::none_of(vec.begin(), vec.end(), [](bool v) { return v; });

You can't find out if all the elements in a vector are true without actually checking every element of the vector. Best-case, you reinterpret the memory differently and check more than 1 element at a time, but you still have to check everything until you find one that fails your test.

like image 95
Barry Avatar answered Sep 24 '22 10:09

Barry