60 likes | 212 Views
Standard Template Library (STL). Generic Templates. For container classes like Stack or Queue Algorithms are the same for elements of int, float, string, or objects Standard Template Library provides generic templates for container classes
E N D
Generic Templates • For container classes like Stack or Queue • Algorithms are the same for elements of int, float, string, or objects • Standard Template Library provides generic templates for container classes • It also provides generic templates for algorithms like search, sort.
Stack Member Functions • bool empty() • Returns true if stack is empty; false, otherwise • int size() • Returns the size • T top() • Access top element • void push(T item) • Insert element at top • void pop() • Remove element from top
Using STL Template Stack • Include STL stack. • #include <stack> • Instantiate stack of type T. • stack myStack<string>; • Use myStack as usual. string name1 = “Anne”; string name2 = “Ben”; myStack.push(name1); // insert at top myStack.push(name2);cout << myStack.top();
QueueMember Functions • bool empty() • Returns true if queue is empty; false, otherwise • int size() • Returns the size • T front () • Access front element • T back() • Access back element • void push(T item) • Insert element at back • void pop() • Remove element from front
Using STL Template Queue • Include STL queue. • #include <queue> • Instantiate queue of type T. • stack myQ<string>; • Use myQ as usual. string name1 = “Anne”; string name2 = “Ben”; myQ.push(name1); // insert at back myQ.push(name2);cout << myQ.front ();