2017-02-27 104 views
-2

編輯: 我並不是指效率更高效的程序運行,但我的意思是它是一個更快的方式來編寫if語句。將多個值與同一變量進行比較時,使用'!='運算符的最簡潔方法是什麼?

我想找到一種方法來減少我的代碼效率。 例如:if(x!=10 && x!=20 && x!=30){} // etc`

我嘗試這樣做,我試過多種其他的方法:

if(x!=(10 && 20 && 30){} 

它不工作。有沒有辦法縮小這個if語句的大小?

+0

將值放入數組中,使用for循環。 「if」語句會很小,因爲您將變量與數組插槽進行比較。 –

+6

如果你正在尋找效率,我保證你吠叫錯誤的樹。這是沒有辦法讓你的代碼變慢的地方。簡介第一。 –

+2

你之前試過一個探查器嗎?也許你正試圖優化一些不影響性能的東西...... – Jepessen

回答

2

的一種方式是使用一個switch

switch (x) 
{ 
    case 10: 
    case 20: 
    case 30: 
     break; 
    default: 
     // do something ... 
     break; 
} 

的另一種方法是使用陣列(或equivilent STL容器,像std::vectorstd::array):

#include <algorithm> 

const int okValues[] = {10, 20, 30}; 
const int *end = &okValues[3]; 

if (std::find(okValues, end, x) == end) 
{ 
    // do something ... 
} 

#include <vector> 
#include <algorithm> 

std::vector<int> okValues; 
okValues.push_back(10); 
okValues.push_back(20); 
okValues.push_back(30); 

/* or, in C++11 and later: 
std::vector<int> okValues {10, 20, 30}; 
*/ 

if (std::find(okValues.begin(), okValues.end(), x) == okValues.end()) 
{ 
    // do something ... 
} 

// C++11 and later only... 

#include <array> 
#include <algorithm> 

std::array<int, 3> okValues = {10, 20, 30}; 

if (std::find(okValues.cbegin(), okValues.cend(), x) == okValues.cend()) 
{ 
    // do something ... 
} 

另一種方法是使用std::set

#include <set> 

const int arr[] = {10, 20, 30}; 
const std::set<int> okValues(arr, arr+3); 

/* or, in C++11 and later: 
const std::set<int> okValues {10, 20, 30}; 
*/ 

if (okValues.find(x) == okValues.end()) // or cend() in C++11 and later 
{ 
    // do something ... 
} 

或者,在特定的3示例值的非常特殊的情況:

int result = x/10; 
int remainder = x % 10; 

if ((result < 1) || (result > 3) || (remainder != 0)) 
{ 
    // do something... 
} 
+0

這是一種不同的方式,但在代碼長度或性能方面沒有更高的效率? –

+1

您能解釋一下交換機解決方案的效率更高嗎? –

+1

@FrançoisAndrieux:根據優化,而不是調用多個if語句,編譯器可能能夠分析switch類型的情況並創建更有效的跳轉表,從而允許給定的輸入值直接跳轉到默認的代碼而不必評估其他值。 –

2

有沒有一種方式,以減少這個if語句的大小? ...並不意味着程序運行效率更高,但...更快的方式來編寫if語句。

我認爲這意味着你想要的字符數少於if (x!=10 && x!=20 && x!=30)和/或「比較容易」,而不是代碼比運行得更快。

一種方法,類似於雷米的answer,使用set。憑藉實用程序,如:

bool in(int x, const std::initializer_list<int>& values) 
{ 
    const std::set<int> s{ values }; 
    return s.find(x) != s.cend(); 
} 

if語句現在是if (!in(x, { 10, 20, 30 }))。這(幾乎)會減少總體字符數,並且可能會比!=&&多次更容易輸入。

不是一個in()功能,你可以重載運營商像!=

bool operator !=(int x, const std::set<int>& s) { 
    return s.find(x) == s.cend(); 
} 

,然後用它

using si = std::set<int>; // si == set<int> 
if (x != si{ 10, 20, 30 }) { } 

忽略using,這是相當簡潔和!=語法相匹配。請注意,您的開發人員可能不會喜歡這一點,因爲與「正常」方式(您想要避免的方式)相比,這會是一種不尋常的習慣用法。

相關問題