在这里,使用几个IF条件或SWITCH-CASE进行编码可能会很好

coding with several IF conditions or is SWITCH-CASE might be good here?

本文关键字:SWITCH-CASE 编码 很好 条件 IF 几个 在这里      更新时间:2023-10-16

我有一个vector<ClassA>(比如my_vector,这个ClassA本身是ClassB的向量),我想写if condition来测试这样的条件:

(1)。如果只有一个元素不为空,而其他元素都为空,(如my_vector的大小是5,我应该测试这个非空的例如my_vector[0], my_vector[1],…)

(2)也适用于两个元素不为空而其他元素为空的情况(其他配对类似)

(3)同样,三个或三个以上的元素不为空

我在想如何编码这个

这是我的尝试

if (!my_vector[0].empty() && my_vector[1].empty() && my_vector[2].empty() && .. &&  
         my_vector[4].empty()){ //process 1}
else if (!my_vector[1].empty() && my_vector[0].empty() && my_vector[2].empty() && ..){ 
         //process 2}
else if(!my_vector[2].empty() && my_vector[0].empty() && my_vector[1].empty() && ..){
        //process 3}
...
...
else if (!my_vector[0].empty() && !my_vector[1].empty() && my_vector[2].empty() && ..   
         my_vector[4].empty()){ //process n}
else if (!my_vector[0].empty() && !my_vector[2].empty() && my_vector[1].empty() && ..   
         my_vector[4].empty()){ //process n+1}
....
....
else if (!my_vector[0].empty() && !my_vector[1].empty() && !my_vector[2].empty() &&    
         my_vector[3].empty() && my_vector[4].empty()){ //process p}
....
like wise

这真的很难测试,任何有条理的方法都无法做到。

使用<algorithm>中的count_if模板函数和lambda,您将获得一个紧凑而清晰的解决方案:

unsigned int non_empties = std::count_if(myvector.begin(), myvector.end(), [](const ClassA & c) { 
     return !c.empty();
});
if (non_empties == 1) {
  // process 1
} else if (non_empties == 2) {
  // process 2
} else if (non_empties >= 3) {
  // process 3
}

<algorithm>库令人惊讶地经常被忽视,尽管它提供了像这样的真正实用的解决方案。

如果空/非空元素的配对无关紧要,则可以遍历集合以获得空元素的数量:

int size = my_vector.size();
int emptyCount = 0;
for (int i = 0; i < size; i++) {
    emptyCount += (my_vector[i].empty() ? 1 : 0);
}
if (emptyCount == 0) {
    // no elements are empty
} else if (emptyCount == 1) {
    // only one element is empty
} else if { emptyCount == 2) {
    // two elements are empty
} ...

最后,使用此方法,您仍然需要为每个条件使用if/else-if;但是,这可以扩展为使用百分比(如果您的集合增长到随机大小)。

定义一个模式数组(概念上是bool的2D数组)。然后依次遍历每一行,找到匹配的行。然后调用与该行对应的相关函数(您可能需要一个函数指针数组)。

也许c++11的新函数all_of, none_of可以帮到你。

你可以这样写

auto iter_begin = my_vector.begin();
auto iter_end = my_vector.end();
auto is_empty = [](decltype(*iter_begin) const & param){ return param.empty();};
auto is_not_empty = [](decltype(*iter_begin) const & param){ return !param.empty();};
if(iter_begin->empty() && all_of(iter_begin + 1, iter_end, is_empty ))
else if(all_of(iter_begin, iter_begin + 1, is_not_empty) && all_of(iter_begin + 2, iter_end, is_empty))
else if(all_of(iter_begin, iter_begin + 2, is_not_empty) && all_of(iter_begin + 3, iter_end, is_empty))

等等