c++同时检查所有数组值

c++ check all array values at once

本文关键字:数组 检查 c++      更新时间:2023-10-16

我想做的是检查一个布尔数组,看看其中是否有3个或更多个被设置为true。我能想到的唯一方法是对每个可能的组合使用if语句,因为有十个bool,所以有很多。有人对如何最好地做这件事有什么建议吗。

这将是最简单的方法:

std::count(bool_array, std::end(bool_array), true) >= 3

唯一的问题是,即使在找到3之后,它仍在继续计数。如果这是一个问题,那么我会使用锐齿的方法。

旁注

我决定为我的个人图书馆设计一个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;
}

为了你的目的,你会这样使用它:

n_or_more_of(bool_array, std::end(bool_array), [](bool b) { return b; }, 3);

更简单的方法是循环遍历数组:

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;

无论何时将数组元素设置为TRUE值,都可以递增全局计数器。这将是最简单的方法。在代码中的任何一点,全局数组都会告诉您数组中TRUE元素的数量。

另一件事是,如果你要保留多达32个布尔值,你可以使用一个int变量。int是32位(在Win32中),您可以存储32个bool。

char x = 0; //  00000000 // char is 8 bits
// TO SET TRUE
x = x | (1 << 4); // 00010000
x = x | (1 << 7); // 10010000
// TO SET FALSE
x = x & ~(1 << 4); // 10010000 & 11101111 => 10000000
// TO CHECK True/False
if( x & ~(1 << 4) )

如果它是一个数组,您要做的就是在它上面循环并计算true的数量。但恐怕你指的是某种比特模式,对吧?

为什么不计算true的数量,然后在数字为3或更高的情况下做一些事情:

int sum = 0;
for (int i = 0; i < length; i++){
  if (arr[i]){
    sum++;
  }
}
if (sum >= 3){
  // do something...
}

您可以循环遍历并构建阵列的位掩码表示,然后可以并行地与多达CHAR_BIT * sizeof (unsigned long)进行比较:

unsigned long mask = 0;
for (std::vector<bool>::const_iterator it = flags.begin(), end_it = flags.end();
     it != end_it;
     ++it)
{
  if (*it)
    mask |= (1 << (it - flags.begin()));
}
if (mask & (0xaa3)) // or whatever mask you want to check
{
}

这假设您正在查找模式,而不仅仅是想计算数组中true标志的数量。

只需循环遍历数组,计算设置为true的布尔数。

/**
 * @param arr The array of booleans to check.
 * @param n How many must be true for this function to return true.
 * @param len The length of arr.
 */
bool hasNTrue(bool *arr, int n, int len) {
    int boolCounter;
    for(int i=0; i<len; i++) {
        if (arr[i]) boolCounter++;
    }
    return boolCounter>=n;
}

那就这么叫吧

hasNTrue(myArray, 3, myArrayLength);

将布尔值存储为整数中的位。然后应用一个小技巧。