2017-06-01 73 views
1

說我有這個如何檢查矢量中的兩個元素是否按順序排列?

vector<int>SequentialByOne{1, 2, 3, 4, 5} //would like to search each element 
//in the vector and if it is sequential a boolean value returns true 


vector<int>notSequential{1, 6, 5, 8, 9} // This would return false 


vector<int>notSequentialButOrdered{1, 3, 6, 9, 20} // This would return false 


// So far I can get it to return true if the next number 
// is bigger than the previous but can't figure out 
// how to check that the next number is only one bigger. 

這是一個撲克手電梯我工作的學校項目。我有一個有序的5個數字的矢量,現在我需要搜索該矢量以查找它們是否按照精確的順序+1。

這是我到目前爲止

sort(hand.begin(), hand.end()); // This is the vector name 

int a; 
{ 
    for(int i = 0; i < 4; i++) 
    { 
     if(hand[i] < hand[i + 1] - 1) 
      a++; 
    } 
} 

bool has_straight 
{ 
    if(a == 5) 
     return true; 
} 
+2

不太清楚是什麼問題。如果你想檢查平等而不是不平等,那麼就做,如果(手[I] =手[I + 1] + 1)'而不是'如果(手[I] <手[I + 1] - 1)' – user463035818

+1

檢查'hand [i + 1] - hand [i] == 1'?或者說,檢查'hand [i + 1] - hand [i]!= 1',如果是true,則返回false。 –

+2

你現在的代碼有什麼問題?如果您希望某人查看您的代碼,請訪問:https://codereview.stackexchange.com/ – Lanting

回答

2

既然你已經排序的vector你可以檢查(假設矢量無重複)如果第一個和最後一個元素之間的差爲4:

hand.back() - hand.front() == 4 
相關問題