[英]Deque Implementation
我對我在Internet上找到的代碼有疑問,該代碼使用deque來查找元素的最大值 -
#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::deque<int> Qi(n);
創建一個包含n
元素的雙端隊列,全部為零。 push_back
操作在后面添加了更多元素,因此deque之后有2 * n
元素。 Qi.front()
與Qi[0]
相同。
所有這些都有詳細記錄,例如這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.