how to print out all elements in a std::stack or std::queue conveniently

后端 未结 8 1709
忘掉有多难
忘掉有多难 2020-12-14 20:46

If I do not to want to create a new container in order to do so?

相关标签:
8条回答
  • 2020-12-14 21:49
    1. If you need to do this, then stack or queue is not the correct choice of container.
    2. If you still insist on doing this, the best way is to make a copy and pop elements off of it and print them. I'm not going to suggest another way because there's no point.
    0 讨论(0)
  • 2020-12-14 21:50

    It can be easily done using recursion you just need to know when to re-add the next element

    For Stack

    void print(stack<char> &s)
    {
        if(s.empty())
        {
            cout << endl;
            return;
        }
        char x= s.top();
        s.pop();
        print(s);
        s.push(x);
        cout << x << " ";
     }
    

    And this one is For Queue

    void print(queue<char> &s,int num)
    {
        if(!num)
        {
            cout << endl;
            return;
        }
        char x= s.front();
        s.pop();
        cout << x << " ";
        s.push(x);
        print(s,--num);
    }
    

    Good Luck

    0 讨论(0)
提交回复
热议问题