我在Windows 7 64位上使用Microsoft VS 2013
我在TutorialsPoint上找到了以下简单的Stack实现
http://www.tutorialspoint.com/cplusplus/cpp_templates.htm
虽然这只是一个简单的例子,但我希望将“弹出”的内容返回给调用者。就像现在一样,你必须访问top()然后pop()顶部才能获得我想要的功能。
我尝试将“void pop()”更改为“T pop()”,然后在实现中修改pop()的返回类型,但编译器拒绝无法转换字符串类型。
首先,不应该更好的实现返回值“popped”
,如果是的话,
如何修改代码以便我返回“弹出”?
如果不清楚,我想使用:
cout << stringStack.pop() << std::endl;
而不是下面需要的两行。
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack
{
private:
vector<T> elems; // elements
public:
void push( T const& ); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const // return true if empty.
{
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const& elem)
{
// append copy of passed element
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop ()
{
if (elems.empty())
{
throw out_of_range( "Stack<>::pop(): empty stack" );
}
// remove last element
elems.pop_back();
}
template <class T>
T Stack<T>::top () const
{
if (elems.empty())
{
throw out_of_range( "Stack<>::top(): empty stack" );
}
// return copy of last element
return elems.back();
}
int main()
{
try
{
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
// manipulate int stack
intStack.push( 7 );
cout << intStack.top() <<endl;
// manipulate string stack
stringStack.push( "hello" );
stringStack.push( "world" );
cout << stringStack.top() << std::endl;
stringStack.pop();
cout << stringStack.top() << std::endl;
stringStack.pop();
cout << stringStack.top() << std::endl;
return 0;
}
catch ( exception const& ex )
{
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
答案 0 :(得分:4)
BTW有一个std::stack
你要求“更好”的代码来保存一行代码,正如其他答案所暗示的那样。
template <class T>
T Stack<T>::pop ()
{
T ret = elems.top():
elems.pop_back();
return ret;
}
这可能会复制更多在可能存在例外情况下可能不安全的元素 - 例如记忆力不足。
有关于此的详细guru of the week。将top
和pop
分开可以更容易在存在异常的情况下使容器保持一致状态。
答案 1 :(得分:1)
答案 2 :(得分:1)
T pop()
{
const T popped = top();
// original code of pop goes here.
return popped
}
关于你的问题
不应该是更好的实现返回值“popped”
通常,返回一个对象可能会导致复制,这可能会引发异常,因为它可能需要额外的资源。这很危险 - 你可能会得到一个资源紧张的系统,因此你想通过弹出东西来释放东西(例如)。问题是 - 你不能,它只需要更多的资源。