C++ C+中数组中所有元素的或/和成员的优雅方式+;11?
我有一个C++ C+中数组中所有元素的或/和成员的优雅方式+;11?,c++,c++11,C++,C++11,我有一个 struct A { bool field; }; 因此,对于数组A[32],我想检查该数组中的所有元素是否都将字段设置为true。这样做的好方法是什么?我可以考虑使用std::acculate。在C++ 11中最好的方法是?< /p> < P>一个“优雅”的C++方式。 std::位集a; 然后,您可以使用以下选项来测试: 所有位都设置为true,a.all() 任何位都设置为true,a.any() 所有位均未设置为true,a.none() 似乎最适合您的问题 std
struct A {
bool field;
};
因此,对于数组A[32]
,我想检查该数组中的所有元素是否都将字段
设置为true。这样做的好方法是什么?我可以考虑使用std::acculate
。在C++ 11中最好的方法是?< /p> < P>一个“优雅”的C++方式。
std::位集a;
然后,您可以使用以下选项来测试:
- 所有位都设置为true,
a.all()
- 任何位都设置为true,
a.any()
- 所有位均未设置为true,
a.none()
- 似乎最适合您的问题
std::all_of(std::begin(a), std::end(a), [](const A &a){return a.field;});
除了
#包括std::所有的#你可能需要#包括std::begin
和std::end
@nwp这两件事我很讨厌。首先,大多数直到C++17才可用。其次,对于布尔值的简单检查没有默认谓词。@Markransem好吧,您可以基于std::all_of
编写自己的all_of
,这样就省去了编写lambda的需要。我可能不会。@nwp我也不会,我只会使用老式的for循环。
std::all_of(std::begin(a), std::end(a), [](const A &a){return a.field;});