【发布时间】:2013-03-10 08:03:23
【问题描述】:
我对我在 Internet 上找到的代码有疑问,该代码使用双端队列来查找元素的最大值 --
#include <iostream>
#include <deque>
using namespace std;
void test(int arr[], int n)
{
std::deque<int> Qi(n);
int i;
for (i = 0; i < n; ++i)
{
while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back(); // Remove from rear
Qi.push_back(i);
}
cout << arr[Qi.front()];
}
// Driver program to test above functions
int main()
{
int arr[] = {12, 1, 78, 90, 57, 89, 56};
int n = sizeof(arr)/sizeof(arr[0]);
test(arr, n);
return 0;
}
我的问题是当我没有做任何 Qi.push_front() 时 Qi.front() 如何给出正确的索引?
但是下面的代码给了我一个 0
void test(int arr[], int n)
{
std::deque<int> Qi(n);
int i;
for (i = 0; i < n; ++i)
{
Qi.push_back(i);
}
cout << arr[Qi.front()];
}
对不起,如果我听起来很愚蠢.. deques 新手...
谢谢
【问题讨论】:
-
这是一种复杂的方式来完成这项任务。您实际上可以用 std::vector 替换 std::deque ,它仍然可以以相同的方式工作并且会更有效(但仍然会令人费解)。您只需要一个 int 即可找到最大的元素或一个索引。
标签: c++ data-structures stl deque