我对我在互联网上找到的代码有疑问,它使用一个双队列来寻找元素的最大值--
#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()];
}如果我听起来很愚蠢,很抱歉..新手。
谢谢
发布于 2013-03-21 07:46:57
std::deque<int> Qi(n);使用全为零的n元素创建一个双端队列。push_back操作在后面添加了更多的元素,因此之后的双端队列就有了2 * n元素。Qi.front()与Qi[0]相同。
所有这些都有很好的文档记录,例如here。
https://stackoverflow.com/questions/15536901
复制相似问题