我知道您可以将向量作为堆栈的存储容器,但我想知道您是否可以将向量中的数据类型作为堆栈存储。因此,如果我有一个名为 vector1 的向量,vector1.at(2) 是否可以返回堆栈而不是诸如 int 或 double 之类的数据类型?我希望当向量的大小加倍时,它可以在程序运行时创建更多堆栈,因为我不知道运行时需要多少个堆栈。
答案 0 :(得分:0)
std::vector
被设计为模板,因此它可以存储任何数据类型。模板参数可以根据需要简单或复杂。如果您希望向量的每个元素都是 std::stack<int>
,则将其设为向量的模板参数。
std::vector< std::stack<int> > vector1;
// ^^^^^^^^^^^^^^^----------------The vector's template argument
复合容器可能会让人感到困惑,因此请记住正在使用哪个容器。外部容器是一个向量。元素(堆栈)可以添加insert
、emplace
、push_back
等。
vector1.emplace_back(); // Add an empty stack to the vector
内部容器(模板参数)是 std::vector::at
的返回类型。像 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
答案 1 :(得分:-1)
答案是肯定的,您在评论中提出的问题的答案是:
registerWithEureka: false
另外,看看这个例子:
stack_name.push(element);