习惯性地反转堆栈? C++标准库试图尽可能地为所有容器提供尽可能多的接口。然而,有一只害群之马指出: #include <algorithm> #include <stack> int main() { std::stack<int> s; std::reverse(std::begin(s), std::end(s)); }
这样做的“标准”方式是什么?请不要使用特别的黑客或复杂的方法。您的代码看起来不错。最后,只需习惯性地反转堆栈? C++标准库试图尽可能地为所有容器提供尽可能多的接口。然而,有一只害群之马指出: #include <algorithm> #include <stack> int main() { std::stack<int> s; std::reverse(std::begin(s), std::end(s)); },c++,c++-standard-library,C++,C++ Standard Library,这样做的“标准”方式是什么?请不要使用特别的黑客或复杂的方法。您的代码看起来不错。最后,只需std::swap(s,s2)。如果需要就地反转,也可以使用std::vector而不是std::stack。然后你可以在上面使用std::reverse std::stack<int> s; std::stack<int> s2; while (!s.empty()) { s2.push(s.top()); s.pop(); } while (!s2.empty(
std::swap(s,s2)
。如果需要就地反转,也可以使用std::vector
而不是std::stack
。然后你可以在上面使用std::reverse
std::stack<int> s;
std::stack<int> s2;
while (!s.empty())
{
s2.push(s.top());
s.pop();
}
while (!s2.empty())
{
s2.top(); // do something with it
s2.pop();
}