Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 21

ec.addError(Error(3, “Unable to read file”)); ec.addError(Error(1, “Incorrect entry from user”)); ec.addError(Error(10, “Unable to allocate memory!”));

while (true) { try {

Error e = ec.getError(); cout << e << endl;

} catch (out_of_range& ) {

cout << “Finished processing errors\n”; break;

}

}

return (0);

}

stack

The stack is almost identical to the queue, except that it provides “last-in, first-out” (LIFO) semantics instead of FIFO. The template definition looks like this:

template <typename T, typename Container = deque<T> > class stack;

You can use any of the three standard sequential containers as the underlying model for the stack.

Stack Operations

Like the queue, the stack provides push() and pop(). The difference is that push() adds a new element to the top of the stack, “pushing down” all elements inserted earlier, and pop() removes the element from the top of the stack, which is the most recently inserted element. The top() method returns a const reference to the top element if called on a const object and a non-const reference if called on a non-const object.

pop() does not return the element popped. If you want to retain a copy, you must first retrieve it with top().

The stack supports empty(), size(), and the standard comparison operators. See the Standard Library Reference resource on the Web site for details.

Stack Example: Revised Error Correlator

Suppose that you decide to rewrite the previous ErrorCorrelator class so that it gives out the most recent errors instead of those with the highest priority. You can simply substitute a stack for the priority_queue in the ErrorCorrelator class definition. Now, the Errors will be distributed from the class in LIFO instead of priority order. Nothing in the method definitions needs to change because the push(), pop(), top(), and empty() methods exist on both the priority_queue and stack.

#include <ostream> #include <string>

594