如何正确打印堆栈的向量

How to properly print a vector of stacks?

本文关键字:向量 堆栈 打印 何正确      更新时间:2023-10-16

我创建了一个堆栈向量。每个堆栈都包含一个整数编号。代码构建和运行,但在我的过载函数中给出了" 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;
}