Search code examples
c++data-structuresstldeque

Deque Implementation


I have question regarding the code I found on Internet which uses a deque for finding the max of the element --

 #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;
}

My Question is how is Qi.front() giving the right index when I have not done any Qi.push_front() ?

But the following code gives me a 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()];   
}

Sorry If I am sounding stupid .. New to deques ...

Thanks


Solution

  • std::deque<int> Qi(n); creates a deque with n elements, all zero. The push_back operations add further elements at the back, so afterwards the deque has 2 * n elements. Qi.front() is identical to Qi[0].

    All this is well-documented, e.g. here.