c++ - 双端队列实现

标签 c++ data-structures stl 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()];   
}

抱歉,如果我听起来很愚蠢......双端队列新手......

谢谢

最佳答案

std::deque<int> Qi(n);使用 n 创建一个双端队列元素,全部为零。 push_back操作在后面添加更多元素,因此双端队列之后有 2 * n元素。 Qi.front()Qi[0] 相同.

所有这些都有详细记录,例如here .

关于c++ - 双端队列实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15536901/

相关文章:

python - 在 C++ 中使用来自 OpenCV 矩阵的特征将图像旋转 90 度

java - 需要在 java 中使用迭代器的帮助

c# - 用于识别重复值的数据结构

java - 解析应用程序名称并为每种类型生成字符串

c++ - 池容器的最佳数据结构是什么?

c++ - 在哪里可以找到有关 "int C::*"用法的说明?

c++ - 如何使用用户输入在 C++ 中正确填充二维数组?

c++ - 如何编写启用 ADL 的尾随返回类型或 noexcept 规范?

c++ - 我应该编写自己的数据结构来处理语义解析还是直接在编译器项目中使用 STL

c++ - "The application failed to initialize properly (0xc000007b)."