2015-10-15 69 views
1

对不起,没有那么难以捉摸的标题,但这里是我用来解释我的问题的一段代码!如何处理while循环中的多个类似条件?

while(motors[0].cycle <= maxcycle 
    && motors[1].cycle <= maxcycle 
    && motors[2].cycle <= maxcycle 
    && motors[3].cycle <= maxcycle 
    && motors[4], etc ...) 

如何避免我while()循环打字很长的情况,因为我总是检查相同的参数,只是我的结构的指标正在发生变化。

+4

http://en.cppreference.com/w/cpp/algorithm/all_any_none_of – rici

回答

6

我该如何避免输入这么长的条件,知道我总是检查相同的参数,只有我的结构索引正在改变。

添加一个函数来执行检查并使用while语句中的函数。

// MotorType is my contrived type. Use the right type. 
bool doCheck(MotorType* motors, int count, int maxcycle) 
{ 
    for (int i = 0; i < count; ++i) 
    { 
     if (!(motors[0].cycle <= maxcycle)) 
     { 
     return false; 
     } 
    } 
    return true; 
} 

while(doCheck(motors, count, maxcycle)) 
{ 
} 
+0

哦,是的,似乎它会做的工作!谢谢 ! – Waz

+0

刚刚实施它,它的工作原理,谢谢你的建议。 – Waz

+0

@Waz,不客气。我很高兴它为你工作。 –

0

将条件抽象成方法。

while (allMotorsLessThanMax(motors, countMotors)) { 
... 
} 

然后定义该方法与自己的迭代:

bool allMotorsLessThanMax(Motor motors[], int countMotors) { 
    for (int i = 0; i < countMotors; ++i) { 
    if (maxcycle < motors[i].cycle) { 
     return false; 
    } 
    } 
    return true; 
} 
+1

这看起来不像C++。 – SergeyA

+0

@SergeyA - 你说得对,我错过了语言标签。固定。 –

0

打破它到一个单独的功能,并通过阵列中的单独的功能迭代,并返回它的真正的去所有的方式,通过假如果它没有通过if检查。

0

你可以做一个循环:

while(true) 
{ 
    for(int i = 0, i < number, i++) 
    { 
    if (motors[i].cycle > maxcycle) 
    { 
     break; 
    } 
    } 
    //Do something 
} 
0

所有这一切都表明了除了功能答案在这里做到这一点......嗯,不是neccessarily的最佳途径。这是为什么:

由于循环被放入单独的函数中,并且motors的数量不是常量,因此编译器很可能使用实际循环并且不会展开它。当你计算纳秒时,自然循环是一种性能危险。 然而,最初的例子并没有这个问题,因为它根本没有循环。

解决方案:提供一个函数,它根本不使用循环,或使编译器更容易展开它。

0

把它放在一个拉姆达检查:

#include <algorithm> 

... 
void myFunction(){ 

    auto allCycling = [&]() -> bool { // lambda function, capture by reference 
     return std::all_of(// for every element in the given range 
      motors.begin(), motors.end(), // given range is all of the motors container 
      [](const decltype(motors[0])& motor) -> bool { 
      return motor.cycle <= maxcycle; // check 
      }); 

    while(allCycling()){ 
     //do stuff 
    } 
} 

参照[&]的拉姆达捕获允许您访问在lambda所有的功能范围的变量,而不用担心它们复制的成本。

4

C++ 11或以上,您可以使用拉姆达折定制检查功能成std::all_of的电话:

while (std::all_of(std::begin(motors), std::end(motors), 
        [=](Motor m){ return m.cycle < maxcycle; })) 
{ 
    ... 

Demo

0

我会在TMP版本折腾:

template < size_t I > 
struct check_it 
{ 
    static bool call(motor_type * motors) 
    { 
     return check_it<I-1>::call(motors) && motors[I].cycles <= maxcycles; 
    } 
} 

template < > 
struct check_it<0> 
{ 
    static bool call(motor_type * motors) { return motors[0].cycles <= maxcycles; } 
}; 

while (check_it<42>::call(motors)) { ... } 

编辑:我不一定会推荐这个,但它应该优化到你写的内容。很难说如果它实际上更快。将取决于有多少指令在缓存中,等等......也许吧?如果重要,你会想要进行配置。