在C++中,能否遍历std::stack
?
以下方法不能用于遍历。因为std::stack
没有成员end
。
std::stack<int> foo;
// ..
for (__typeof(foo.begin()) it = foo.begin(); it != foo.end(); it++)
{
// ...
}
在C++中,能否遍历std::stack
?
以下方法不能用于遍历。因为std::stack
没有成员end
。
std::stack<int> foo;
// ..
for (__typeof(foo.begin()) it = foo.begin(); it != foo.end(); it++)
{
// ...
}
由于 c++
的堆栈没有某种类型的迭代器,因此这是带有迭代器的基本堆栈。
MutantStack.hpp
#pragma once
#include <stack>
template <class T>
class MutantStack : public std::stack<T>
{
public:
typedef typename std::stack<T>::container_type::iterator iterator;
typedef typename std::stack<T>::container_type::const_iterator const_iterator;
MutantStack(void) {}
iterator begin(void)
{
return this->c.begin();
}
iterator end(void)
{
return this->c.end();
}
const_iterator cbegin(void) const
{
return this->c.cbegin();
}
const_iterator cend(void) const
{
return this->c.cend();
}
};
for (stack<T> newStack = stack; !newStack.empty(); newStack.pop()){
T item = newStack.top();
}