gpt4 book ai didi

c++ - 用几个 IF 条件编码或者 SWITCH-CASE 在这里可能很好?

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:16 24 4
gpt4 key购买 nike

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

(1). If only one element is not empty while all others are empty, (as size of the my_vector is five, I should test this non-empty one element case one after the other for e.g. my_vector[0], my_vector[1],..)

(2) also, if two of elements are not empty while others are empty (similarly for other pairs)

(3) similarly, three or more of elements are not empty

我在想怎么写这个

这是我的尝试

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

这真的很难测试,任何有条不紊的方法都可以。提前致谢。

最佳答案

使用 count_if来自 <algorithm> 的模板函数和一个 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>令人惊讶的是,图书馆经常被忽视,但它提供了像这样非常实用的解决方案。

关于c++ - 用几个 IF 条件编码或者 SWITCH-CASE 在这里可能很好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16965904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com