gpt4 book ai didi

c++ - 如何方便地打印出 std::stack 或 std::queue 中的所有元素

转载 作者:IT老高 更新时间:2023-10-28 22:33:35 25 4
gpt4 key购买 nike

如果我不想为此创建一个新容器?

最佳答案

我已经编写了一个片段来进行调试。例如:

std::stack<int> s; // works with std::queue also!
s.push(1);
s.push(2);

std::cout << s; // [ 1, 2 ]

请原谅我的这种骇人听闻的代码!但这是我几个月前写的:

#include <stack>
#include <queue>
#include <ostream>

template <class Container, class Stream>
Stream& printOneValueContainer
(Stream& outputstream, const Container& container)
{
typename Container::const_iterator beg = container.begin();

outputstream << "[";

while(beg != container.end())
{
outputstream << " " << *beg++;
}

outputstream << " ]";

return outputstream;
}

template < class Type, class Container >
const Container& container
(const std::stack<Type, Container>& stack)
{
struct HackedStack : private std::stack<Type, Container>
{
static const Container& container
(const std::stack<Type, Container>& stack)
{
return stack.*&HackedStack::c;
}
};

return HackedStack::container(stack);
}

template < class Type, class Container >
const Container& container
(const std::queue<Type, Container>& queue)
{
struct HackedQueue : private std::queue<Type, Container>
{
static const Container& container
(const std::queue<Type, Container>& queue)
{
return queue.*&HackedQueue::c;
}
};

return HackedQueue::container(queue);
}

template
< class Type
, template <class Type, class Container = std::deque<Type> > class Adapter
, class Stream
>
Stream& operator<<
(Stream& outputstream, const Adapter<Type>& adapter)
{
return printOneValueContainer(outputstream, container(adapter));
}

您可以像任何其他支持的类型一样流式传输 std::stackstd::queue!

关于c++ - 如何方便地打印出 std::stack 或 std::queue 中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com