说我有这个
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 个数字的 vector ,现在我需要搜索该 vector 以查找它们是否按精确顺序 +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;
}
最佳答案
因为您已经对 vector
进行了排序,您可以检查(假设 vector 中没有重复项)第一个元素和最后一个元素之间的差异是否为 4:
hand.back() - hand.front() == 4
关于c++ - 如何检查 vector 中的两个元素是否按一个顺序排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302532/