T of data, and the int N denoting the number of stacks. The NStack class is templated on two parameters: The type Typename std::list>::iterator stack_successor Hence, the type of this iterator is std::list>::iterator. to the list of the same type, templated on typename T. 3) next element in the same stack: We use std::iterators 2) stack_id to denote the stack it belongs to. int type can be defined by specializing this template, itself is templated on the Data type T. Main structure to be held in the std::list. empty_stack: When Pop or Top is called on an empty stack with the corresponding stack id.stack_id_out_of_bound: When the stack_id passed in the Push, Pop, or Top methods exceeds the number of stacks.This code also handles two types of exceptions: Here is a listing that illustrates how we can use templates, std::list, and iterators to avoid the low-level pointer manipulation, and at the same time provide a generalized implementation of the Three Stacks. All of these methods work with iterators. Use std::list method, especially, push_front, front, and erase instead of pointer manipulation.Use std::list::iterator as the data-type of stack_successor instead of node pointer. ![]() Maintain a std::list of elements instead of defining our own Node structure. ![]() Thus, in order to use iterators, we are going to It define two operators: (1) * for dereferencing, and (2) ++ for iterating through the container. According to the definition,Īn iterator is an object that points to a container (like std::list), and has the ability to iterate through the elements of the container. We are going to use std::iterator interface instead of pointers to keep track of the stack successors. But we can do better - by using yet another C++ language construct - templates. Sure, we can simply use the number of stacks as the parameters to the class constructor.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |