我想请您帮助解决我遇到的这个问题,我需要编写一个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
。