bob*_*mac 2 c++ arrays boolean
我想要做的是检查一个bool数组,看看它们中是否有3个或更多被设置为true.我能想到的唯一方法就是为每个可能的组合使用if语句,因为有十个bool.任何人都有任何关于如何做到这一点的建议.
Ben*_*ley 10
这将是最简单的方法:
std::count(bool_array, std::end(bool_array), true) >= 3
Run Code Online (Sandbox Code Playgroud)
唯一的问题是,即使找到了它就会继续计数3.如果这是一个问题,那么我会使用sharptooth的方法.
边注
我决定以std::all_of/any_of/none_of我个人图书馆的风格制作算法,也许你会发现它很有用:
template<typename InIt, typename P>
bool n_or_more_of(InIt first, InIt last, P p, unsigned n)
{
while (n && first != last)
{
if (p(*first)) --n;
++first;
}
return n == 0;
}
Run Code Online (Sandbox Code Playgroud)
为了您的目的,您可以像这样使用它:
n_or_more_of(bool_array, std::end(bool_array), [](bool b) { return b; }, 3);
Run Code Online (Sandbox Code Playgroud)
更简单的方法是循环遍历数组:
int numberOfSet = 0;
for( int i = 0; i < sizeOfArray; i++ ) {
if( array[i] ) {
numberOfSet++;
//early cut-off so that you don't loop further without need
// whether you need it depends on how typical it is to have
// long arrays that have three or more elements set in the beginning
if( numberOfSet >= 3 ) {
break;
}
}
}
bool result = numberOfSet >= 3;
Run Code Online (Sandbox Code Playgroud)