Sunteți pe pagina 1din 10

CSE 1018Y COMPUTER PROGRAMMING

Standard Template Library: Queue and List

QUEUE

Queue is an ordered list of items


queues are specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and removed from the other end. queues are implemented as containers adaptors.

OPERATIONS OF A QUEUE

push() to add an item to a queue pop() to remove an item from the queue size() returns the number of items in a queue empty() to check if a queue is empty front() returns the first element of a queue back() returns the last element of a queue

EXAMPLES
queue<int> myqueue; int x=2, y=3;
myqueue.push(8); myqueue.push(9); myqueue.push(y); x = myqueue.front(); myqueue.pop(); myqueue.push(18); myqueue.push(myqueue.front()); x = myqueue.front(); myqueue.push(22); cout<< myqueue.back()<<endl;
4

EXAMPLE CONT.
while (myqueue.empty()) { y = myqueue.front(); myqueue.pop(); cout << y << ; } cout << x << endl; myqueue.push(77); myqueue.push(16); myqueue.front() = myqueue.front()-myqueue.back(); cout << "myqueue.front() is " << myqueue.front() << endl;
5

EXAMPLE
#include <iostream> #include <queue> using namespace std; int main () { queue<int> myqueue; int sum (0); for (int i=1;i<=10;i++) myqueue.push(i); while (!myqueue.empty()) { sum += myqueue.front(); myqueue.pop(); } cout << "total: " << sum << endl; return 0; }

LIST

Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence. List iteration is on both directions. List containers are implemented as doubly-linked lists (i.e can store each of the elements they contain in different and unrelated storage locations.) The ordering is kept by the association to each element of a link to the element preceding it and a link to the element following it.
7

OPERATIONS ON A LIST
push_front: inserts element at beginning of the list pop_front: delete first element of the list push_back: add element at the end of the list pop_back: deletes last element from the list insert: insert elements to a list clear: clear content of a list front: access first element of the list back: access last element of the list empty: check whether list container is empty size: return the size of the list ITERATORS begin: return iterator to the beginning of the list end: return iterator to the end of the list

EXAMPLES
#include <iostream> #include <list> int main () { list<int> mylist; int sum=0; mylist.push_back (10); mylist.push_back (20); mylist.push_back (30); cout<<Size of mylist = <<mylist.size()<<endl; while (!mylist.empty()) { sum = sum+mylist.back(); mylist.pop_back(); } cout << Sum of elements of mylist = " << sum << '\n'; return 0; }

REFERENCES
C++ How to program, Fifth Edition, Deitel & Deitel www.cplusplus.com

10

S-ar putea să vă placă și