向量可以包含堆栈吗?

Can a vector contain stacks?

我知道您可以将向量作为堆栈的存储容器,但我想知道您是否可以将数据类型作为堆栈存储在向量中。因此,如果我有一个名为 vector1 的向量,是否可以 vector1.at(2) return 堆栈而不是 int 或 double 等数据类型?我希望当向量的大小加倍时,它可以在程序运行时创建更多堆栈,因为我不知道在运行时需要多少堆栈。

答案是肯定的,您在评论中的问题的答案是:

stack_name.push(element);

另外,看这个例子:

  #include <iostream>
#include <vector>
#include <stack>

using namespace std;
int main() 
{
  stack< int, vector<int> > stckk; 
  stckk.push(2);
  stckk.push(21);
  stckk.push(45);
  stckk.push(76);
  cout <<"Top Element is "<<stckk.top() << endl;
  
  while(!stckk.empty())
   { stckk.pop();
     if(stckk.empty())
     cout << "The Stack is now Empty." << endl;
   } 
  return 0;
}

A std::vector 被设计为模板,因此它可以存储任何数据类型。模板参数可以根据需要简单或复杂。如果您希望向量的每个元素都是 std::stack<int>,则将其设为向量的模板参数。

std::vector< std::stack<int> > vector1;
//           ^^^^^^^^^^^^^^^----------------The vector's template argument

复合容器可能会让人感到困惑,因此请记住使用的是哪个容器。外层容器是一个向量。可以添加元素(堆栈)insertemplacepush_back

vector1.emplace_back();  // Add an empty stack to the vector

内部容器(模板参数)是 std::vector::at 的 return 类型。像 vector1.at(2) 这样的表达式求值为堆栈(假设 vector1.size() 至少为 3)。该堆栈可以照常操作,使用 vector1.at(2) 作为其名称。

vector1.at(2).push(7);  // Push 7 onto the third stack in the vector
vector1[2].pop();       // Remove the top element of the third stack in the vector