[英]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
的内容并将它们一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<<
但对于来自std::
命名空间的原始类型重载它通常不是一个好主意):
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.