如何正确打印堆栈向量?

时间:2019-02-13 22:12:23

标签: c++

我创建了一个向量堆栈。每个堆栈包含一个整数。该代码生成并运行,但是它在我的重载函数中给出了“ 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;
}

2 个答案:

答案 0 :(得分:1)

问题是

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;
}

答案 1 :(得分:1)

此方法正在进行中(并且myPrint可以更改为operator<<,但是对于{{1}的 raw 类型的重载它通常不是一个好主意}命名空间):

std::
相关问题