在几个IF条件下编码或SWITCH-CASE可能在这里好吗?

时间:2013-06-06 15:18:17

标签: c++ if-statement

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

  

(1)。如果只有一个元素不为空而其他元素都为空,则为(如        my_vector的大小是五,我应该测试这个非空的        元素案例一个接一个地用于例如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

这是一种非常难以测试的方法,任何有条不紊的方法都可以。 提前谢谢。

4 个答案:

答案 0 :(得分:6)

使用<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>库经常被忽视,而它提供了非常实用的解决方案。

答案 1 :(得分:1)

如果空/非空元素的配对无关紧要,您可以遍历您的集合以计算有多少是空的:

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用于每个条件;但是,这可以扩展为使用百分比(如果您的集合增长到随机大小)。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

也许新的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))

等等