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 
相关问题