简体   繁体   English

C ++组合检查是否满足条件子集

[英]C++ Combinatoric check that subset of conditions are met

I want to ensure as an example that 2/3 values are within a given threshold. 作为示例,我想确保2/3值在给定阈值内。 The code below accomplishes this but I'm wondering if there is a more generic approach. 下面的代码完成了此操作,但我想知道是否有更通用的方法。

struct foo {
  int id;
  float item1;
  float item2;
  float item3;
}

bool ConditionCheck(foo val1, foo val2, foo val3) {
  int count = 0;
  if (abs(val1.item1 - val2.item1) < val3.item1) {
    count++;
  }
  if (abs(val1.item2 - val2.item2) < val3.item2) {
    count++;
  }
  if (abs(val1.item3 - val2.item3) < val3.item3) {
    count++;
  }

  if (count >= 2) {
    return true;
  }
  return false;
}

The issue stems for the custom structs else having parameters as arrays: 问题源于自定义结构,其他结构的参数为数组:

// assuming array holds: [id, item1, item2, item3]
bool ConditionCheck(float (&val1)[4], float (&val2)[4], float(&threshold)[4]) {
  int count = 0;
  for (unsigned int i = 1; i < 4; ++i) {
    if (abs(val1[i] - val2[i]) < threshold[i]) {
      count++;
    }
  }
  if (count >= 2) {
    return true;
  }
  return false;
}

You can use an array of pointers to member: 您可以使用指向成员的指针数组:

bool ConditionCheck(foo val1, foo val2, foo val3) {
  float foo::* ptrs[3] = { &foo::item1, &foo::item2, &foo::item3 };
  return std::count_if( &ptrs[0],
                        &ptrs[3], 
                        [&](float foo::* p)
                        {
                            return abs(val1.*p - val2.*p) < val3.*p;
                        }) >= 2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM