【问题标题】:How can I print out the contents of std::stack and return its size?如何打印 std::stack 的内容并返回其大小?
【发布时间】:2012-09-19 20:05:29
【问题描述】:

在 c++ 中如何打印堆栈的内容并返回其大小?

std::stack<int>  values;
values.push(1);
values.push(2);
values.push(3);

// How do I print the stack?

【问题讨论】:

  • 你想要什么样的格式?没有办法让所有人都满意。
  • stack 是什么意思?你的意思是std::stack&lt;&gt; 还是call stack 或其他一些堆栈。请在细节上更具体一点。
  • 说如果我有一堆整数 a,并且我通过 a.push(1) a.push(2) a.push(3) 推动整数,我怎么能打印出 1,2 ,3?

标签: c++ stack


【解决方案1】:

不使用“特殊技术”的简单方法是通过

递归

由于没有限制std::stack&lt;&gt;的成员函数pop ()不能使用等,我们可以使用下面的递归算法。

算法:

  1. 基本情况:如果堆栈为空 => 返回。
  2. 弹出顶部元素并将其存储在变量中。
  3. 打印存储的值。
  4. 递归调用堆栈的其余元素。
  5. 再次将元素推入堆栈。

尽管进行了弹出操作,但堆栈不会丢失其元素,因为我们在打印堆栈的其余部分后以相同的顺序再次推送它们。

这是上述算法的代码:

void printStack (std::stack <int> &values) {
    
    if (values.empty ()) {
        return;
    }

    int topElement = values.top ();
    values.pop ();

    std::cout << topElement << std::endl;

    printStack (values);

    values.push (topElement);
}

以上代码的输出:

3
2
1

这将按从上到下的方式打印元素。

如果您希望元素从下到上打印,只需切换递归调用和std::cout 语句即可。

void printStack (std::stack <int> &values) {
    
    if (values.empty ()) {
        return;
    }

    int topElement = values.top ();
    values.pop ();

    printStack (values);

    std::cout << topElement << std::endl;

    values.push (topElement);
}

输出:

1
2
3

而std::stack&lt;&gt;的成员函数size ()可以用来获取栈的大小。

std::cout << values.size () << std::endl;

【讨论】:

    【解决方案2】:

    嗯,一个将近 10 年的问题。无论如何,这里有一个额外的答案。

    首先:堆栈的大小由 std::stack.size() 给出。

    然后,在现代 C++ 中,越来越多地使用带有算法的 STL。因此,以下解决方案利用了这一点。前提是堆栈使用连续内存。目前这是有保证的。

    输出是通过单线完成的。

    请看下面的例子:

    #include <vector>
    #include <stack>
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    #include <sstream>
    
    using Number = int;
    using UnderlyingContainer = std::vector<Number>;
    using Stack = std::stack< Number, UnderlyingContainer>;
    
    std::istringstream testData("5 8 1 4 9 3");
    
    int main()
    {
        // Put the test data onto the stack
        Stack stack{ UnderlyingContainer {std::istream_iterator<Number>(testData),std::istream_iterator<Number>()} };
    
        // Print the test data
        if (not stack.empty())
            std::copy(&stack.top() + 1 - stack.size(), &stack.top() + 1, std::ostream_iterator<Number>(std::cout, "\n"));
    
        return 0;
    }
    
    

    这是完全有效和可靠的代码。这里稍微解释一下。

    我们想要输出数据,所以我们将其复制到 ostream_iterator。 ostream_iterator 引用一个流(是的,你也可以放一个 open ofstream)和分隔符。也许你想使用“”。

    副本的来源是 2 个迭代器。而且,是的,指针是迭代器。而且,我们为 std::stack 使用了保证的连续内存。因此,我们只需计算 2 个指针并将它们交给 std::copy。

    如果你想使用显式迭代器。开始了 。 .

    #include <vector>
    #include <stack>
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    #include <sstream>
    
    using Number = int;
    using UnderlyingContainer = std::vector<Number>;
    using Stack = std::stack< Number, UnderlyingContainer>;
    
    using StackIterator = const Number *;
    
    std::istringstream testData("5 8 1 4 9 3");
    
    int main()
    {
        // Put the test data onto the stack
        Stack stack{ UnderlyingContainer {std::istream_iterator<Number>(testData),std::istream_iterator<Number>()} };
    
        // Print the test data
        // Get iterators
        StackIterator end = &stack.top() + 1;
        StackIterator begin = end - stack.size();
    
        if (not stack.empty())
            std::copy(begin, end, std::ostream_iterator<Number>(std::cout, "\n"));
    
        return 0;
    }
    

    因此您可以为堆栈创建迭代器。但是,请注意:

    std::stack 有意将其元素隐藏在底层。因此,如果您对数据进行写访问,我会将其视为设计错误。通过 const 指针/迭代器进行读取访问对我来说是可以的。但也许你应该更好地使用 std::vector 。 . .

    【讨论】:

      【解决方案3】:

      您可以复制堆栈并逐个弹出项目以转储它们:

      #include <iostream>
      #include <stack>
      #include <string>
      
      int main(int argc, const char *argv[])
      {
          std::stack<int> stack;
          stack.push(1); 
          stack.push(3); 
          stack.push(7); 
          stack.push(19); 
      
          for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
              std::cout << dump.top() << '\n';
      
          std::cout << "(" << stack.size() << " elements)\n";
      
          return 0;
      }
      

      输出

      19
      7
      3
      1
      (4 elements)
      

      在这里现场观看:http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f

      【讨论】:

      • 不会清空他的堆栈吗?有没有不弹出的解决方案?
      • 不会,因为我先复制它(到dump)。没有弹出的解决方案是没有堆栈的解决方案。如果您需要随机访问(通用)容器,请不要使用堆栈容器适配器。
      • 不是,这只是stack 类型的简写。我将编辑以 C++03 风格拼出它:)
      【解决方案4】:

      std::stack 和 std::queue 都是通用容器的包装器。该容器可作为protected 成员c 访问。使用c,您可以获得对元素的高效访问;否则,您可以只复制堆栈或队列并破坏性地访问副本的元素。

      c使用示例:

      #include <iostream>     // std::wcout, std::endl
      #include <stack>        // std::stack
      #include <stddef.h>     // ptrdiff_t
      using namespace std;
      
      typedef ptrdiff_t   Size;
      typedef Size        Index;
      
      template< class Elem >
      Size nElements( stack< Elem > const& c )
      {
          return c.size();
      }
      
      void display( stack<int> const& numbers )
      {
          struct Hack
              : public stack<int>
          {
              static int item( Index const i, stack<int> const& numbers )
              {
                  return (numbers.*&Hack::c)[i];
              }
          };
      
          wcout << numbers.size() << " numbers." << endl;
          for( Index i = 0;  i < nElements( numbers );  ++i )
          {
              wcout << "  " << Hack::item( i, numbers ) << endl;
          }
      }
      
      int main()
      {
          stack<int>  numbers;
          for( int i = 1;  i <= 5;  ++i ) { numbers.push( 100*i ); }
      
          display( numbers );
      }
      

      【讨论】:

        【解决方案5】:

        打印std::stack 的元素而不弹出它们的唯一方法是编写一个扩展std::stack (here's an example) 的适配器。否则,您应该用 std::deque 替换您的堆栈。

        【讨论】:

        • 为什么是std::deque 而不是std::vector?
        • std::deque 是 std::stack 使用的默认容器。没有特殊原因。
        【解决方案6】:

        http://www.cplusplus.com/reference/stl/stack/ 它的尺寸很容易使用:

        cout << mystack.size();
        

        对于其余部分,我在文档中没有看到任何内容,但是您应该在推送堆栈时打印堆栈的内容,或者有一个列表来保存元素的记录,以便打印它,完成测试后不要忘记删除它

        【讨论】:

          猜你喜欢
          • 2020-08-03
          • 2013-09-04
          • 2020-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-10
          • 1970-01-01
          相关资源
          最近更新 更多