c++同时检查所有数组值
c++ check all array values at once
我想做的是检查一个布尔数组,看看其中是否有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);
将布尔值存储为整数中的位。然后应用一个小技巧。
相关文章:
- 试图让变量检查数组中的某些内容
- 如何在C++中检查2D数组中负值的输入验证
- 使用for循环检查数组中的重复项
- 检查TCHAR数组输入是否为带符号整数C++
- std::数组边界检查如何工作?
- 检查输入 std::array 指针数据是否等于某个常量数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- C++ 检查结果数组中有多少次数字
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 有没有办法在c ++中清除空数组,请检查下面的代码以获取说明
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- 如何检查二维数组上的周围数字?
- 检查反向数组是否与原始数组相同
- 如何检查cin是否与数组中的一组数字匹配
- 如何检查数组中是否没有值
- 如何检查字节数组是protobuf序列化字节数组还是普通字节数组
- 检查彩虹数组(检查数组的反向样式是否与自身匹配)
- 使用数组检查连续性
- c++ 根据随机生成的数组检查用户输入的值
- 使用字符串数组检查用户输入