如何正确打印堆栈的向量
How to properly print a vector of stacks?
我创建了一个堆栈向量。每个堆栈都包含一个整数编号。代码构建和运行,但在我的过载函数中给出了" stackoverlfow"错误。我敢肯定,这很简单,我看不到。我感谢任何帮助。谢谢
std::ostream& operator<<(std::ostream &os, std::vector<std::stack<int>> &vectOfStacks)
{
os << vectOfStacks;
return os;
}
int main()
{
int n;
int sum = 0;
int sizeOfNum=0;
std::stack<int> s;
std::vector<std::stack<int>> vectOfStacks;
std::cout << "How many numbers you want to add? " << std::endl;
std::cin>>n;
int* value = new int[n];
for (int i = 0; i < n; i++)
{
std::cout << "Enter integers" << std::endl;
std::cin >> value[i];
for (int j = 0; j < n; j++) // same the integer one digit at a time into a stack
{
s.push(value[i] - '0');
}
vectOfStacks.push_back(s); // push the stack for this number into vector
std::cout << vectOfStacks;
sum = sum + value[i];
}
std::cout << "Sum of the integers = " << sum <<std::endl;
//addingLargeNumber(vectOfStacks);
/*for (std::vector<std::stack<int>>::iterator it = vectOfStacks.begin(); it != vectOfStacks.end(); ++it)
std::cout << *it << ' ';
for (int i = 0; i < vectOfStacks.size(); i++)
{
std::cout << vectOfStacks[i];
}*/
//std::cout << vectOfStacks[i];
delete[] value;
system("pause");
return 0;
}
问题是
os << vectOfStacks;
翻译成
operator<<(os, vectOfStacks);
因此,您在该功能中具有无限的递归。您需要将实现更改为迭代vectOfStacks
的内容,然后将它们流到os
。
std::ostream& operator<<(std::ostream &os, std::stack<int> const& st)
{
if ( !st.empty() )
{
// Can't iterate over the contents of const std::stack. Need to make
// a copy of the input object and use the copy to print the contents.
std::stack<int> st_copy = st;
while ( !st_copy.empty() )
{
int top = st_copy.top();
st_copy.pop();
os << top << " ";
}
}
return os;
}
// Note the addition of const to the second argument.
std::ostream& operator<<(std::ostream &os, std::vector<std::stack<int>> const& vectOfStacks)
{
for ( std::stack<int> const& st : vectOfStacks )
{
os << st;
}
return os;
}
这里正在进行(可以将myPrint
更改为 operator<<
,但是对于 raw 类型的 std::
namespace中的 raw 类型通常不是一个好主意):
std::ostream &myPrint(std::ostream &os, std::vector<std::stack<int>> const &vs) {
os << "vec:n";
for (auto s : vs) {
os << "t(stack): ";
while(!s.empty()){ os << s.top() << ' '; s.pop();}
os << 'n';
}
return os;
}
相关文章:
- 对象接收堆栈溢出异常 c++ 的排序向量
- 对象向量是否在堆或堆栈上分配C++?
- 在C++中使用队列和堆栈对 2 个向量进行加减
- 是否可以在堆栈上创建向量
- 堆栈在函数中弹出仍然显示在主函数中。调用不应该通过引用给定的向量吗
- 附加到具有非动态分配堆栈的向量
- 如何正确打印堆栈的向量
- 从分配在堆栈上的对象指针的向量中删除元素
- 链表与动态数组用于使用向量类实现堆栈
- 向量的向量,堆与堆栈(C++)
- 制作数组堆栈和向量的二维数组
- 将向量从堆栈复制到堆上
- 堆栈分配的向量如何在 C++ 中扩展
- 存储在对象向量上的基于堆栈的指针具有很长的使用寿命
- C++向量的堆栈分配
- 在C++中,是在堆栈或堆上的函数中创建的向量或映射
- 为什么存储在 STL 向量中的堆栈分配元素C++即使超出范围也仍然处于活动状态
- 我怎样才能实现堆栈的向量
- 为什么这不会导致堆栈溢出?其中是存储的全局向量(堆栈或堆)
- 我如何修复这段代码,使它不会pop_back或back()如果向量/堆栈是空的