如果数组中的所有值都为true,则退出函数

时间:2016-04-12 13:39:46

标签: c++ arrays control-flow

我想添加一个类的一个成员的简单功能:我想退出该函数,以防某些布尔(2d)数组的所有值都是true

在简单的1d数组中,我可以这样做:

int SIZE = 10;
std::vector<bool> myArray(SIZE, true);
int i = 0;
while(myArray[i] and i < SIZE){
    ++i;
    }
if(i == SIZE){
    return;
    }
// rest of the code for array not all true

可能没有更快的方法(减去边际优化),但我发现它有点难看。有更好的方法吗?

=========================================

最后我决定实施:

{
bool allTrue = true;
for(int i = 0; i < SIZE1 and allTrue; ++i)
    for(int j = 0; j < SIZE2 and allTrue; ++j)
        allTrue &= myArray[i][j];
if(allTrue)
    return;
}

4 个答案:

答案 0 :(得分:3)

您可以使用std::all_of中的<algorithm>

if (std::all_of(myArray.begin(), myArray.end(), [](bool b) {return b;})) {
    return;
}

答案 1 :(得分:1)

其中一个解决方案:

int my2Da[][2] = {{true, true},{true, true},{true, true}};
int *pa = my2Da[0];
bool flag=true;
for (int i=0;flag && i<(sizeof my2Da)/(sizeof (int));flag &= pa[i++]);
//flag indicates about the result

答案 2 :(得分:0)

可能是所有价值观?这样:

std::all_of

如果你熟悉迭代器和lambda,那么using namespace boost; const char* line = // ... size_t line_length = // ... // ... tokenizer<escaped_list_separator<char> > line_tokenizer( line, line + line_length, escaped_list_separator<char>('\\', ',', '\"'));

答案 3 :(得分:0)

对于2d矢量,您可能想要将其分解:

#include <vector>
#include <algorithm>


bool all_true(const std::vector<bool>& v)
{
  return std::all_of(std::begin(v), std::end(v), [](const auto& b) { return b; });
}

bool all_true(const std::vector<std::vector<bool>>& vv)
{
  return std::all_of(std::begin(vv), std::end(vv), [](const auto& v) { 
    return all_true(v); 
  });
}

void test()
{
  std::vector< std::vector< bool > > d2 /* = initalise 2d vector */;


  while(!all_true(d2))
  {
    // things you want to do
  }


}