首页 > 解决方案 > 检查struct的至少一个成员变量是否为真

问题描述

在我的代码中,我使用在程序启动时初始化的以下类型的结构。

struct Parameters
{
    Parameters()
    {
         bla = false;
         foo = false;
         bar = false;
         // and so on ...    
    }
    bool bla;
    bool foo;
    bool bar;
    // and so on ...
};

我程序中的实际结构包含大约 100 个布尔变量。在运行期间,某些变量的参数可能会更改为true.

我想知道是否有一种简单的方法来检查我的结构的至少一个变量是否为true. C++ 是否提供了迭代结构的功能,以便我可以避免手动检查大约 100 个变量?

我想像

for (bool item : Parameters)
{
    if (item == true)
    {
        return true;
    }
}

标签: c++loopsstructiterator

解决方案


编辑:我已经完全改变了这个答案,因为我被告知之前的答案可能会导致某些编译器设置出现问题。

你这样做的方法是创建一个指向所有结构成员的成员数组的指针。通过这种方式,您可以轻松地遍历它们。当然这并不理想,因为当结构中有很多成员时,它可能会变得很长,所以我建议使用布尔映射,但如果你真的想要一个结构,你可以这样做。

首先创建一个指向所有成员的成员数组的全局指针:

constexpr bool yourstruct::* arrName[<yourNumberOfElements>] = {
  &yourstruct::elem1,
  &yourstruct::elem2,
  &yourstruct::elem3,
  // continue until you have all your members here
};

然后你可以创建一个这样的函数:

bool isAtLeastOneTrue(struct yourstruct* p1, int size){
  for(int i = 0; i<size;i++){
    if(p1->*arrName[i])
      return true;
  }
  return false;
}

然后你可以调用该函数来查看是否有任何成员为真。

isAtLeastOneTrue(&yourstructInstance, <yourStructSize>)

这是一些如何使用它的示例

struct test{
  test(){
    a1 = false;
    a2 = false;
    a3 = false;
    a4 = false;
    a5 = false;
    a6 = false;
    a7 = false;
    a8 = false;
    a9 = true;
    a10 = false;
    a11 = false;
  }
  bool a1;
  bool a2;
  bool a3;
  bool a4;
  bool a5;
  bool a6;
  bool a7;
  bool a8;
  bool a9;
  bool a10;
  bool a11;

};

constexpr bool test::* ptma[11] = { // pointer to member array
  &test::a1,
  &test::a2,
  &test::a3,
  &test::a4,
  &test::a5,
  &test::a6,
  &test::a7,
  &test::a8,
  &test::a9,
  &test::a10,
  &test::a11
};



bool isAtLeastOneTrue(struct test* p1, int size){
  for(int i = 0; i<size;i++){
    if(p1->*ptma[i])
      return true;
  }
  return false;
}


int main() {
  test a;
 
  cout << isAtLeastOneTrue(&a, 11) << endl;
}

推荐阅读