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

标签 c++

例如,我想确保 2/3 的值在给定的阈值内。下面的代码实现了这一点,但我想知道是否有更通用的方法。

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

问题源于自定义结构 else 将参数作为数组:

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

最佳答案

您可以使用指向成员的指针数组:

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

关于C++组合检查是否满足条件子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973835/

相关文章:

c++ - -std=c++11 编译器标志在某些时候会默认吗?

c++ - 长文件 (15 MB) 上的 CStdioFile::GetPosition 有几个字节错误

C++查找USB设备挂载点

c++ - MFC120u.dll "missing"

c++ - Qt DBus : register object that implements multiple interfaces

c++ - MS CryptoAPI 在带有 CryptAcquireContext() 的 Windows XP 上不起作用

python - C++ 中的数组内数组类似于 python 中的列表中的列表

c++ - 带有包含和源路径的 CMake - 基本设置

c++ - 使用宏定义打印格式参数

c++ - 我的简单字符串实现出错了