Faculty of Arts, Computing, Engineering and Sciences COURSE: COMPUTER AND NETWORK ENGINEERING. YEAR OF STUDY: 2008/2009. MODULE: OBJECT OREINTED METHODS. MODULE LEADER: ALAN GOUD ASSIGNMENT: STL: QUEUES,MAPS AND ASSOCIATED ITERATORS & ALGORITHMS DEADLINE: 03 APRIL 2008. SUBMITTED BY: RAJKRISHNA DEEPAK VUYYURU(17040603) VINESH KUMAR REDDY LANKA(17028670) SWAMY CHANDAN DONDAPATI(17035523) T. K RAJA SHEKAR (17040235) STL: QUEUES,MAPS AND ASSOCIATED ITERARTORS & ALGORITHMS Introduction: C++ is an object-oriented programming (OOP) language which is the best language for creating large-scale applications. It is similar to “c” language with added object oriented functions . A high-level programming language developed by Dennis Ritchie and Brian Kernighan at Bell Labs in the mid 1970s,Later in 1998 an industry standaized it as an object oriented compile language . C++ is an object oriented language that can be compiled and run on a server via the source file of sample”c” and then compiled into an executable file. Many people avoid the standard library due to its performance. In fact, the whole standard library was designed with performance in mind, and often things will compile to code that is just as efficient as a solution you write yourself. Another very common (and somewhat related) reason not to use standard library functionality is that people refuse to use anything they did not program themselves in their programs. While it is very educational to make everything yourself at least once, if you want to be productive you'll have to start using other people's code, it is available and it is well tested. Standard Template Library: A generic library to manage collections of data with efficient algorithms. TEMPLATE: A document or file having a preset format, used as a starting point for a particular application so that the format does not have to be recreated each time it is used: a loan amortization template for a spreadsheet program. LIBRARY : A collection of standard programs and subroutines that are stored and available for immediate us. S T L: The Standard Template Library (STL) was one of the major efforts that took place during the standardization of C++ . STL is the result of years of dedicated research into the possibilities of generic programming and is a major part of the standard C++ Library. STL provides an incredible amount of generic programming power that can be immediately useful in your programs. It provides general purpose, templatized classes and functions that implement many popular and commonly used algorithms and data structures, including, for example, support for vectors, lists, queues, and stacks. It also defines various routines that access them. Because the STL is constructed from template classes, the algorithms and data structures can be applied to nearly any type of data. The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features. To understand and use the STL, you must have a complete understanding of the C++ language, including pointers, references, and templates. Frankly, the template syntax that describes the STL can seem quite intimidating. Although it looks more complicated than it actually is, while there is nothing in STL that is any more difficult than the other features of C++. The Standard Template Library is mainly composed of generic container class templates and a set of many efficient template algorithms designed to work with, and manipulate, the containers. The classes declared and defined in STL use templates to their fullest capacity, enabling truly generic programming for C++ programmers. STLCOMPONENTS: STL contains six kinds of components: Containers iterators algorithms function objects adopters allocators. Container: Container classes are c++ classes that act as container for other objects, such as an array or a linked list. A common type of a container is it's an "Array", a built in feature of c++.containers are more powerful, flexible than arrays. Containers have its own memory as well as its track record of objects they hold. Container classes provide structured, dynamic storage in reusable modules that you can easily plug in to any program where they might be needed. Containers are called as building blocks as they are used to create object -oriented programs and which make the internals of a program to construct more easily. Containers Classification: Container characteristics: Sequential: Vector : Provides a linear and contiguous storage (similar to an array) that allows fast inserts at the end only. list It is an implementation of a doubly linked list that allows fast inserts anywhere. deque Provides a linear but non-contiguous storage that allows fast inserts at extremities. Associative multiset It is an implementation of set where duplicates are allowed and provides fast associative lookup. set It is an implementation of set where no duplicates are allowed and provides fast associative lookup. multimap It is an implementation of a key to value mapping structure where a single key can be mapped to many values (1 to many mappings). map It is an implementation of a key to value mapping structure where a single key can only be mapped to one value (1 to 1 mapping). Adapter stack It is an implementation of a first in last out data structure. queue It is an implementation of a first in first out data structure. priority_queue A queue that maintains items in a sorted order. Standard sequence container: vector ,dequeue ,list and string containers are said to be sequence conatiners where Vector defines a dynamic array, Dequeue creates a double-ended queue, List provides a linear list and String provides functions for gathering information about a string's size, length, capacity, maximum length and other characteristics. Sequence containers are nothing but here elements are stored in sequence. All the above four containers have their own differences in their performance of main sequence container types. Standard Associate container: Set, Multiset, Map and Multimap containers are said to be associate containers where Set defines in which every element is unique, Multiset is one in which each element is not necessarily unique, Map is one that store key/value pairs in which each key is associated with only one value, Multi map is same as map but it may be associated with two or more values of one key. Standard Adapter container: An Adaptor is a generic component that modifies the interface of another component. An adapter transforms one thing into another .For example, the containers which creates a standard queue is an adapter for the dequeue container. stack, queue, Priority queue are called as adapter containers where stack contains dynamically allocated memory, queue is an abstract data type, priority queue is same as queue but differs depending upon the priority given. Containers are usually implemented using template classes, various place holder data types. The name of the place holder types are arbitary in template class so they are defined by declaring them as typedefed Versions of the following: Size_type some integral type roughly equivalent size_T reference a reference to an element const_reference A const reference to an element difference_type can represent difference between two addresses iterator an iterator const_iterator A const iterator reverse_iterator A reverse iterator const_reverse_iterator A const reverse iterator value_type the type of value stored in the container (often the same as the generic type T) allocater_type the type of allocator key_type the type of key key_compare the type of function that compare's two keys mapped_type the type of value stored in a map (same as a Generic type T) value_compare the type of a function that compares two values pointer the type of a pointer const_pointer the type of a const pointer container_type the type of a container Queue: Queue is a data structure that represents a line. The elements that are placed in the queue are the longest one in the queue that can be accessed first. The data items enter the queue at the Rear and leaves from the Front The operation used to enter the data item into the queue is called Enqueue and operation used to remove the data item is called Dequeue. Restricted form of a Dequeue is queue: Elements are entered from one end and pulled out from another end. Coming to the programming part Dequeue can be used instead of a queue in functionality. When you want to emphasize a queue like behavior then use a queue than a Dequeue .For serving elements (placing elements by other elements) in a model system queues are often used. if no container is given then by default Dequeue is being taken. Example: A queue is like person or people waiting in a line(this is also called as queue) at the ticket counter(at theaters) the line can get longer or even can finish earlier but people must leave only thru front line. in terms of computer add data from the back of queue and take it from the front of the queue. THIS IS ALSO KNOWN AS "first IN first OUT ". The template specification is shown below : Template <class T, Class container = deque <T> > class queue T--> type of data being stored Container: Used to hold queue and the constructor is followed below. explicit queue (const Container & cnt = Container ()); < explicit queue >: queue() constructor creates an empty queue < const Container & cnt > : list as a container for queue. < Container() > : A protected object called C of type container. Example: #include <iostream> #include <queue> #include <string> using namespace std; int main() { queue<string> q; // insert three elements into the queue q.push("These "); q.push("are "); q.push("more than "); // read and print two elements from the queue cout << q.front(); q.pop(); cout << q.front(); q.pop(); // insert two new elements q.push("four "); q.push("words!"); // skip one element q.pop(); // read and print two elements cout << q.front(); q.pop(); cout << q.front() << endl; q.pop(); // print number of elements in the queue cout << "number of elements in the queue: " << q.size() << endl; } Member functions: Map: The map class provides look up using a rapid key based look up. Duplicates are not allowed. The elements in the map are in the form of pairs containing keys and values. Insertions and deletions are possible at any where in the map. To insert an element into map requires a pair object that has the key and a value. The map cannot store more than one value against each key because each key can only appear once, if you try and add a second instance of the same key, then that will supersede the existing one. Some Map Access Functions ------------------------- Purpose ------- begin() Returns iterator pointing to first element end() Returns iterator pointing _after_ last element swap( , ) Swap two elements insert( , ) Insert a new element size() Number of elements in map max_size() Maximum possible number of elements in map empty() [] True if map is empty "Subscript search" access operator [] is the most frequently used operator in the STL maps’s APL function.Theassociated key value allows us to use convenient access and modified values for this operator.if novalue is given to key associated then default constructed is associated and reference is returned to new value.if value is associated then reference is returned to the value.therefore maps areused for implemented collections of one to one mappings. the Person class has a default c++ constructor that initializes an object of this class to a default null value, which has a blank name, a negative age value and a blank National Insurance Number. The program allows the user to enter some values of Person class into a map that associated the value of the name member to the objects . Then the program allows the user to enter some key values and returns the references to the associated objects. Example: #include <map> #include <iostream> #include <string> using namespace std; class Person { private: string name; int age; string nINumber; public: Person(void) { name = ""; age = -1; nINumber = ""; } Person(string inName, int inAge, string inNINumber) { name = inName; age = inAge; nINumber = inNINumber; } string& getName(void) { return name; } int getAge(void) { return age; } string& getNINumber(void) { return nINumber; } bool operator == (const Person& p) { return (name == p.name); } bool operator < (const Person& p) { return (age < p.age); } bool isNULL(void) { return ((name == "") && (age == -1) && (nINumber == "")); } }; void populatePeople(map<string, Person>& peopleMap) { char continueFlag = 'y'; string name; int age; string nINumber; while (continueFlag == 'y') { cout << "Enter name "; cin >> name; cout << "Enter age "; cin >> age; cout << "Enter National Insurance number "; cin >> nINumber; Person p(name, age, nINumber); peopleMap[name] = p; cout << "Enter y to add another, any other key to exit:"; cin.get(); continueFlag = cin.get(); cin.get(); } } void interrogateMap(map<string, Person>& peopleMap) { char continueFlag = 'y'; string name; while (continueFlag == 'y') { cout << "Enter name to search "; cin >> name; Person p = peopleMap[name]; if (p.isNULL()) { cout << "No entry found for " << name << endl; } else { cout << p.getName() << ":" << p.getAge() << ":" << p.getNINumber() << endl; } cout << "Enter y to find another, any other key to exit:"; cin.get(); continueFlag = cin.get(); cin.get(); } } int main(void) { map<string, Person> peopleMap; populatePeople(peopleMap); interrogateMap(peopleMap); return(0); } An interaction with this program is listed below, Enter name Omar Enter age 38 Enter National Insurance number 3157 Enter y to add another, any other key to exit:y Enter name Amna Enter age 33 Enter National Insurance number 7531 Enter y to add another, any other key to exit:y Enter name Inde Enter age 30 Enter National Insurance number 1982 Enter y to add another, any other key to exit:n Enter name to search Inde Inde:30:1982 Enter y to find another, any other key to exit:y Enter name to search Sajid No entry found for Sajid Enter y to find another, any other key to exit:y Enter name to search Amna Amna:33:7531 Enter y to find another, any other key to exit: ITERATORS: These are general terms of pointers.Iterators point to other object.iterators are used to iterate a range of objects.if an iterator points one element then it can be increased to the next element. These are generic programmes.because they are the interface between containers and algorithms.iterators take algorithm as argument.So the container must act to access their element to iterators.There is a possibilty of algorithms that operates different kinds of container.Here the stl deals with diffferent concepts which are related to iterators and several pre-defined iterators. DESCRIPTION: Iterators are of six concepts that form the hierarchy.Some are restricted towards the set of operation and other additional functionality.The five concepts used by algorithms are as folllows. ITERATOR TYPES INPUT ITERATOR TERM INLTER ACCESS ALLOWED RETRIVES BUT DOES NOT STORE VALUES. OUTPUT ITERATOR FORWARD ITERATOR RANDOM ACCESS OUTLTER STORES BUT DOES NOT RETRIVE VALUES FORLTER STORES AND RETRIVES VALUES RANDLTER STORES AND RETRIVES VALUES ITERATOR: Among these input and out put iterators are restricted.These iterators donot allow multipass algorithm.Input iterator can onl;y have purmission to read access.It is not possible to assign a new value to the input iterator.out put iterator can only have permission to write access.it is possible to assign a value to the out put iterator.But it is not possible to refer that value. Forward iterators are the refined iterators of input and output iterators.Forward iterators support input and as well as out put iterators which provides the functionality.It is possible to use multipass algorithms with farward iterators.A forward iterator is a constant in which it is possible to access the access ,but can not assign a new value. Bidirecrtional algorithms iterators allow multi pass algorithm.they are different and can support both direction .A bi-directional iterator can be increased to obtain the coming element or can be decremented to obtain the previous element.A forward iterator is required to support forward motion .An iterator can be used to interchange the singly linked list. Finally, random accessiterator allows operation of pointer arthematic,subscripting,find a distance etc.Most iterators are expressed interms of range of iterators. these are two different mechanism to support sort of inference.An order mechanism called ITERATOR TAGS and newer mechanism called ITERATOR TRAITS. Example: // some typedefs typedef map<long, string, less<long> > EmployeeTable; typedef multimap<string, long, cmp_fn> Directory; typedef EmployeeTable::iterator EmpTableIter; int main(void) { EmployeeTable emp_table; // adding some values in employee table, to demostrate different ways of // inserting in a map emp_table.insert(pair<long, string>(7100, "Barney")); emp_table.insert(make_pair(7200, "Fred")); emp_table[7300] = "Joe"; // The correct way to search EmpTableIter Iter = emp_table.find(8000); // not found assert(emp_table.end() == Iter); Iter = emp_table.find(7100); // found assert((*Iter).second == "Barney"); // checking insertion result // case 1 - new entry pair<EmployeeTable::iterator, bool> result = emp_table.insert(make_pair(7400, "Eric")); assert(result.second == true); // case 2 - replacing an old entry result = emp_table.insert(make_pair(7400, "Tolkein")); assert(result.second == false); // Multimap - telephone directory, namve vs phone number // one guy can have more than one phone number Directory d; // insert into map d.insert(make_pair("Fred", 45635)); d.insert(make_pair("Fred", 45634)); d.insert(make_pair("Fred", 45638)); d.insert(make_pair("Fred", 45630)); d.insert(make_pair("Fred Pal", 25635)); Directory::iterator LB = d.lower_bound("Fred"); Directory::iterator UB = d.lower_bound("Fred"); if(LB == UB) { // only one entry for key "Fred" } else { assert((*LB).second == 45635); // first entry assert((*LB).second == 45630); // last entry for(Directory::iterator i = LB; i != UB; ++i) { // work with i } } LB = d.lower_bound("Fred Pal"); UB = d.lower_bound("Fred Pal"); assert( LB == UB); return 0; } TYPES OF ITERATORS: 1.ISTREAM ITERATOR 2.OSTREAMITERATOR 3.REVERSE ITERATOR 4.REVERSE BIDIRECTIONAL ITERATOR 5.INSERT ITERATOR 6.FRONT INSERT ITERATOR 7.BACK INSERT ITERATOR 8.ITERATOR TRAITS 9.INPUT ITERATOR TAG 10.INPUT ITERATOR TAG 11.OUTPUT ITERATOR TAG 12.FORWARD ITERATOR 13.BI DIRECTIONAL ITERATOR TAG 14.INPUT ITERATOR TAG 15.OUTPUT ITERATOR TAG 16.FORWARD ITERATOR TAG Nonstandard Sequence Containers: Nonstandard sequence containers contains slist and rope containers. Slist is singly linked list. Rope is essentially a heavy duty string. Nonstandard Associative Containers. These are hash table based variants like hash_map, hash_multimp, hash_set and hash_multiset. Nonstandard Sequence Containers: Nonstandard sequence containers contains slist and rope containers Slist is singly linked list Rope is essentially a heavy duty string Nonstandard Associative Containers: These are hash table based variants like hash_map, hash_multimp, hash_set and hash_multiset. References: 1. http://www.codersource.net 2. c++ complete Refernce by Herbert Schildt 3. c++ for dummies by Jeff Cosswell 4. http://www.pottsoft.com 5. Data structures in c++ by Angela B.shiflet 6. http://www.sgi.com/tech/stl/