2015-10-15 70 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)) { ... } 

編輯:我不一定會推薦這個,但它應該優化到你寫的內容。很難說如果它實際上更快。將取決於有多少指令在緩存中,等等......也許吧?如果重要,你會想要進行配置。