I want to ensure as an example that 2/3 values are within a given threshold. 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.