gpt4 book ai didi

c++ - 如果数组中的所有值都为真,则退出函数

转载 作者:行者123 更新时间:2023-11-30 01:44:11 26 4
gpt4 key购买 nike

有一个简单的功能我想添加到一个类的成员中:我想退出函数以防某些 bool (2d) 数组的所有值都为 true .

在一维数组的更简单的情况下,我可以这样做:

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;
}

最佳答案

您可以使用 std::all_of来自 <algorithm> :

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

关于c++ - 如果数组中的所有值都为真,则退出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36575070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com