Faculty of Arts, Computing, Engineering and Sciences

plumponionchipsΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

104 εμφανίσεις




Faculty of Arts, Computing, Engineering
and Sciences

C
OURSE:
COMPUTER AND NETWORK ENGINEERING.


YEAR OF STUDY: 2008/2009
.


MODULE: OBJECT OREINTED METHODS
.


MODULE LEADE
R: 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 c
reating 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 serve
r via the source file of sample”
c


and
then compiled into an executable file.


M
any 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 stan
dard 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 L
ibrary:

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 applica
tion 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 Stan
dard 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, i
ncluding, 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, th
e 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 mai
nly 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 m
ake 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 a
nd 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 valu
es (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 implem
entation 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 V
ector
defines a dynamic array,

D
equeue creates a double
-
ended
queue, L
ist



provides a linear list and S
tring 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:


S
et,
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 associ
ated 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 c
ontainers where stack contains dynamically allocated memory, queue
is an abstract data ty
pe, 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
tem
plate class so
they are d
efined
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 re
ference to an element

difference_type

can represent difference between two
addresses

iterator

an

iterator

const_iterator

A const iterator

reverse_iterator

A reverse iterato
r

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

o
f 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

c
onst_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 eleme
nts
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 F
ront
T
he operation used to
enter

the data

item
into the queue is called E
nqueue and operation used to remove the
data item is called
D
equeue.




Restricted form of a D
equeue is queue
:




Elements are entered from one end and pulled out from another
end. Coming t
o the programming

part D
equeue can be used inste
a
d of a queue in
functionality.
When

you want to emphasize a queue like
behavior then use a queue than a
D
equeue .For serving
elements (
placing elements by other elements) in

a model system
queues are often
u
sed. 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
peopl
e 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 contai
ner = 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 em
pty 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 tw
o 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 queu
e


cout << "number of elements in the queue: " << q.size()


<< endl;

}




Member
functions:


Map
:

The map class provides look up using a rapid key b
ased look up.

D
uplicates

are not allowed
. The elements in the map are in the form of pairs cont
aining
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 ag
ainst

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 oper
ator in the STL maps’s APL function
.The
associated
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 valu
e 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 som
e 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 = inNa
me;

age = inAge;

nINumber = inNINumber;


}


string& getName(void)


{


return name;


}


int getAge(void)


{


return age;



}

string& getNINumber(void)

{


return nIN
umber;


}


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<stri
ng, 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() << e
ndl;


}


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 interac
tion 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 o
ther 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 o
ther 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.


T
hese 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


TERM



ACCESS ALLOWED


INPUT ITERATOR

INLTER
RETRIVES BUT DOES







NOT STORE VALUES.


OUTPUT ITERATOR OUT
LTER

STORES BUT DOES NOT









RETRIVE VALUES


FORWARD ITERATOR FORLTER

STORES AND RETRIVES









VALUES


RANDOM ACCESS

RANDLTER
STORES AND RETRIVES










VALUES


ITERATOR
:


A
mong 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 iterator
s.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 e
xpressed 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_tabl
e.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 c
an 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_pai
r("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

1
0.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 c
ontainers
.


Slist is singly linked list
.


R
ope 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:


Nonsta
ndard 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.




Ref
e
rences:

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/