如何检查队列是否使用 STL 排序



我想请您帮助解决我遇到的这个问题,我需要编写一个C++函数,该函数将队列作为参数输入并检查队列中的内容是否按排序顺序排列(使得前面元素最小(。应相应地返回BOOLEAN值。假设队列中没有重复的元素。
我正在尝试了解排序的概念,因此任何帮助将不胜感激,这是我到目前为止尝试过的:

#include "stdafx.h"
#include <iostream>
#include <queue>
using namespace std; 
bool is_Sorted(queue<int> q) {
int my_front = q.front();
int my_back = q.back();
if (my_front==my_back) {
return true;
}
if (my_front+1>my_front) {
return true;
}
}
int main()
{
queue <int> q;
q.push(3);
q.push(4);
q.push(5);
q.push(6);
q.push(7);
is_Sorted(q);
return 0;
}

因为queue不提供不能使用的迭代器:is_sorted

因此,比较需要复制queue或顺序pop和比较queue的元素,然后push将它们放回queue。我选择简单地复制此示例的queue

template <typename T>
bool is_sorted(queue<T> q) {
if(!empty(q)) {
for(T i = q.front(); size(q) > 1U; i = q.front()) {
q.pop();
if(i > q.front()) {
return false;
}
}
}
return true;
}

这个例子显然会产生复制queue的成本,这显然是不可取的。产生此成本是因为queue是作业的错误工具。考虑priority_queue或只是一个vector

最新更新