Lab Manual OOP
Lab Manual OOP
Problem Statement:
Implement a class Complex which represents the Complex Number
data type.Implementthefollowingoperations:
1. Constructor (including a default constructor which creates the
complex number0+0i).
2. Overloadedoperator+toaddtwocomplexnumbers.
3. Overloadedoperator*tomultiplytwocomplexnumbers.
4. Overloaded<<and>>toprintandreadComplexNumbers.
Objectives:
OperatorOverloading
Itisaspecificcaseofpolymorphism
wheredifferentoperatorshavedifferentimplementationsdepending on their arguments. In
C++ the overloading principle applies not only to functions, but tooperators too. That is, of
operators can be extended to work not just with built-in types but alsoclasses. A
programmer can provide his or her own operator to a class by overloading the built-
inoperatortoperform some specificcomputationwhen theoperator isused onobjects
ofthatclass.
AnExample ofOperatorOverloading
Overloadable operators
+ - * / = <> += -= *= /= <<>>
~ &=^= |=&&||%=[]
● typeoperatoroperator-symbol (parameters){/*...*/}
whenapplied to instances of a class. This gives the operator more than one meaning,
or
"overloads"it.Thecompilerdistinguishesbetweenthedifferentmeaningsofanoperatorb
yexaminingthetypes of itsoperands.
Syntax:
return_typeclass_name::operatorop(arg_list)
//functionbody
where,
● Returntypeisthevaluereturnedbythespecifiedoperation
● opistheoperator tobeoverload.
● opisproceedingbythekeywordoperator.
● operatoropis thefunctionname
2. Declaretheoperatorfunctionoperatorop()inthepublicpartofthe
class.Itmay beeitheramemberfunction orafriend function.
3. Definetheoperator functiontoimplementtherequiredoperation
e.g.OverloadingBinaryoperators:
Astatementlike
C=sum(A,B); //functionalnotation
Thisfunctionalnotationcanbereplacedbyanaturallookingexpression
C=A+B; //arithmeticnotation
Algorithm:
Step1:Starttheprogram
Step2: Createaclasscomplex
Step3:Definethedefaultconstructor.
Step 4: Declare the operator function which are going to be overloaded and display
functionStep5: Definetheoverloaded functionssuchas +,-,/,* and thedisplay
function
ForAddition:
(a+bi) + (x + yi) = ((a+x)+(b+y)i)ForMultiplication:
Step9:Displaytheresultusingdisplayfunction
Output:
Defaultconstructorvalue=0+0i
Enterthe1stnumber
Entertherealpart2
Entertheimaginarypart4
Enterthe2ndnumber
Enterthereal part4
Entertheimaginarypart8
Theaddition is6+12i
Themultiplicationis-24+32i
Conclusion:
Hence, we have studied concept of operator overloading.
1. Whatisoperatoroverloading?
2. Whataretherulesforoverloading theoperators?
3. Stateclearlywhichoperators
areoverloadedandwhichoperatorarenotoverloaded?
4. Statetheneedforoverloadingtheoperators.
5. Explainhow theoperators areoverloaded usingthefriendfunction.
6. Whatisthedifferencebetween“overloading”and“overriding”?
7. Whatisoperator function?Describethesyntax?
8. WhenisFriendfunctioncompulsory?Giveanexample?
Assignment No:2
Title: -StudentDatabaseManagementsystem.
Problemstatement: -
Develop an object oriented program in C++ to create a database of
studentinformation system containing the following information: Name, Roll
number, Class,division, Date of Birth, Blood group, Contact address, telephone
number, driving licence no.etc Construct the database with suitable member
functions for initializing and destroying thedata viz constructor, default
constructor, Copy constructor, destructor, static memberfunctions, friend class,
this pointer, inline code and dynamic memory allocation operators-newand
delete.
Objectives:
Tolearntheconceptofconstructor,defaultconstructor,copy,destructor,staticmemberf
unctions,
friendclass,thispointer,inlinecodeanddynamicmemoryallocationoperators-
newanddelete.
Theory:
Constructor:
Aspecialmethodoftheclassthatwillbeautomaticallyinvokedwhenaninstanceoftheclassi
screatedis called as constructor. Following are the most useful features of constructor.
1) Constructor is used forInitializingthevaluestothe data membersof theClass.
2) Constructoristhatwhosenameissameasnameofclass.
3) ConstructorgetsAutomaticallycalledwhenanobjectofclassiscreated.
4) ConstructorsneverhaveaReturnTypeevenvoid.
5) Constructor is of Default, Parameterized and Copy
Constructors.Thevarioustypesof Constructor
areasfollows:-
Constructorscanbeclassifiedinto3types
1. DefaultConstructor
2. ParameterizedConstructor
3. CopyConstructor
1. DefaultConstructor:-
DefaultConstructorisalsocalledasEmptyConstructorwhichhasnoargum
entsandItis Automatically called when we create the object of class but Remember
name of Constructor is sameas name of class and Constructor never declared with the
help of Return Type. Means we can’t declare aConstructor with the help of void
Return Type., if we never Pass or declare any Arguments then thiscalledasthe Copy
Constructors.
2. ParameterizedConstructor: -
This is another type constructor which has some Arguments and
same name as classname but it uses some Arguments So For this, we have to create
object of Class by passing someArguments at the time of creating object with the
name of class. When we pass some Arguments to theConstructor then this will
automatically pass the Arguments to the Constructor and the values willretrieveby
the RespectiveData Membersofthe Class.
3. CopyConstructor: -
This is also another type of Constructor. In this Constructor we pass
the object of classinto the Another Object of Same Class. As name Suggests you
Copy, means Copy the values of oneObject into the another Object of Class .This
is used for Copying the values of class object into ananother objectofclassSowe
callthemasCopyConstructorand ForCopyingthe values Wehave topass the name of
object whose values we wants to Copying and When we are using or passing an
Objecttoa Constructorthenwemusthave to use the&Ampersandor AddressOperator.
4. Destructor:
AsweknowthatConstructoristhatwhich isusedforAssigningSomeValuesto
dataMembersandForAssigningSomeValuesthisMayalsousedSomeMemorysothattofreeu
ptheMemory which is Allocated by Constructor, destructor is used which gets
Automatically Called at theEnd of Program and we doesn’t have to Explicitly Call a
Destructor and Destructor Can’t beParameterized or a Copy This can be only one Means
Default Destructor which Have no Arguments.ForDeclaringaDestructor, wehave touse
~tiled Symbolinfrontof Destructor.
Staticmembers: -
• Onlyonecopyofthatmemberiscreatedfortheentireclassandissharedbyallt
heobjectsofthatclass.
• Itisthevisibleonly withintheclassbutitslifetimeistheentire program.
Static data members of a class are also known as "class variables", because there is
only one
uniquevalueforalltheobjectsofthatsameclass.Theircontentisnotdifferentfromoneobje
ctstaticmembershave the same properties as global variables but they enjoy class
scope. For that reason, and to avoidthem to be declared several times, we can only
include the prototype (its declaration) in the classdeclaration but not its definition
(its initialization). In order to initialize a static data-member we mustinclude a formal
definition outside the class, in the global scope of this class to another. Because it is
aunique variable value for all the objects of the same class, it can be referred to as a
member of anyobject ofthatclassoreven directlyby theclassname
(ofcoursethisisonlyvalidforstaticmembers.
Astaticmemberfunctionhasfollowingproperties: -
● Astaticfunctioncanhaveaccesstoonlyotherstaticmembers(funorvar)declaredin
thesameclass
● AstaticfunctioncanbecalledusingtheclassnameinsteadofitsobjectnameClass_n
ame:: fun_name;
Static member functions are considered to have class scope. In contrast to non static
member functions,these functions have no implicit this argument; therefore, they
can use only static data members,enumerators, or nested types directly. Static
member functions can be accessed without using an objectofthecorresponding
classtype.
Thefollowingrestrictionsapplytosuchstaticfunctions:
1. Theycannotaccessnonstaticclassmemberdatausingthemember-selectionoperators(.or–
>).
2. Theycannotbedeclaredasvirtual.
3. Theycannothavethesamenameasanon-staticfunctionthathasthesameargumenttypes.
Friendfunctions:
Inprinciple,privateandprotectedmembersofaclasscannotbeaccessedfromoutsidethesame
classinwhich they are declared. However, this rule does not affect friends. Friends are
functions or classesdeclared as such. If we want to declare an external function as friend
of a class, thus allowing thisfunction to have access to the private and protected members
of this class, we do it by declaring
aprototypeofthisexternalfunctionwithintheclass,andprecedingitwiththe keywordfriend.
Propertiesoffriendfunction:
thispointer:
C++ uses a unique keyword called this to represent an object that invokes a
member function. Thisis
apointerthatpointstotheobjectforwhichthisfunctionwascalled.Thisuniquepointe
risautomaticallypassedto amember function when itiscalled.
• this pointer stores the address of the class instance, to enable pointer
access of the members to thememberfunctionsof theclass.
• thispointerisnotcountedforcalculatingthesizeoftheobject.
• thispointersarenotaccessibleforstaticmemberfunctions.
• thispointersarenotmodifiable.
Algorithm:
1. Start
2. ReadpersonnelinformationsuchasName,DateofBirth,Bloodgroup,Height,Weight,
InsurancePolicy,number,Contactaddress, telephone number,drivinglicense no..
3. Printallinformationfromdatabase.
4. Stop
Input: -
StudentinformationsuchasName,DateofBirth,Bloodgroup,Height,Weight,InsurancePo
licy,number,contact address, telephone number,drivinglicense no.
Output: -
Defaultvalues:
Sachin 0 IA 11/11/1111AA city9000000000A0101010 A0101010
Sachin(Object)isdestroyed!
Abc (Object)isdestroyed!
create?:1Enter:name,roll,Class,Div,Dob,bg,contact,phon
B123345
abc(Object)isdestroyed
!
Useofcopyconstructor:
Conclusion:
Hence,wehavesuccessfullystudiedconceptofconstructor,default
constructor,copyconstructor,destructor,staticmemberfunctions,friend
class,thispointer,inlinecodeanddynamicmemoryallocationoperators-new
and delete.
Questions:
1. Whatisconceptofconstructor,destructor?
2. Whataretypesofconstructors?
3. WhatisstaticFunction?
4. Whatisfriendfunction?Statetheadvantageofusingthefriendfunction
5. Whatisthispointer?Explainwith examples.
AssignmentNo:3
Title:Creatingaclasswhichusestheconceptofinheritance,displaysdataandda
tamembersandusesthe concept ofexceptionhandling.
Objectives:To learntheconceptofinheritanceandexceptionhandling.
Theory:
Inheritance:
Inheritance in Object Oriented Programming can be described as a
process ofcreating new classes from existing classes. New classes inherit
some of theproperties and behaviour of the existing classes. An existing
class that is"parent" of a new class is called a base class. New class that
inherits propertiesof the base class is called a derived class. Inheritance is
a technique of
codereuse.Italsoprovidespossibilitytoextendexistingclassesbycreatingder
ivedclasses.
Thebasicsyntaxofinheritanceis:
Thereare3accessspecifiers:
Namelypublic,privateandprotected.
public:
This inheritance mode is used mostly. In this the protected member of
BaseclassbecomesprotectedmembersofDerivedclassandpublicbecomespu
blic.
protected:
Inprotected
mode,thepublicandprotectedmembersofBaseclassbecomesprotectedmem
bersofDerivedclass.
private:
InprivatemodethepublicandprotectedmembersofBaseclassbecomeprivate
membersofDerivedclass.
TypesofInheritance
InC++,wehave5differenttypesofInheritance.Namely,
1. SingleInheritance
2. MultipleInheritance
3. HierarchicalInheritance
4. MultilevelInheritance
5. HybridInheritance
SingleInheritance:
Inthistypeofinheritanceonederivedclassinheritsfromonlyonebaseclass.
ItisthemostsimplestformofInheritance.
Syntax:
classsubclass_name:access_modebase_class
{
//bodyofsubclass
};
MultipleInheritance:
Inthistypeofinheritanceasinglederivedclassmayinheritfromtwoor
morethantwobaseclasses.
Syntax:
classsubclass_name:access_modebase_class1,access_modebase_class2,....
{
//bodyofsubclass
};
MultilevelInheritance:
Inthistypeofinheritance,thederivedclass inheritsfromaclass, whichinturninherits
from some other class. The Super class for one, is sub class for theother.
HierarchicalInheritance:
Inthistypeofinheritance,multiplederived classesinheritsfromasinglebaseclass.
HybridInheritance:
HybridInheritanceiscombinationofany2ormoretypesofinheritances.
ExceptionHandling:
Exception handling is part of C++ and object oriented programming. they
areadded in C++ to handle the unwanted situations during program execution.
Ifwe do not type the program correctly then ot might result in errors.
Mainpurposeofexceptionhandlingistoidentify
andreporttheruntimeerrorintheprogram.
Famousexamplesaredividebyzero,arrayindexoutofbounderror,filenotfound,devic
enotfound,etc.
C++exceptionhandlingispossiblewiththreekeywordsiz.try,catchandthrow.Exce
ptionhandlingperformsthefollowingtasks:-
• Findtheprobleminthegivencode.Itisalsocalledashitexception.
• Wereceivetheroe info.It iscalledascatchingtheexception.
• Ittakesthecorrectiveaction.It iscalledasexceptionhandling.
ry{
throwexception
}
catch(argument)
{
...
...
}
//restofthecode
/
Algorithm:
1. Start.
2. CreateclassesPublication,bookandtape.
3. Publicationclasshavingdata memberstitle,price.
4.
ClassBookhavingdatamemberspagesandmemberfunctionsgetdata()andpudata(
).
5. ClassTapehavingdatamembersminutesandmemberfunctions getdata()and
pudata().
6. Createanobjectofclass bookandobjecttofclasstape.
7. Stop.
Output: -
Runyourownprogramandpaste outputhere.
Conclusion:
Hence,wehavesuccessfullystudiedconceptofinheritanceandexcepti
onhandling.
Questions:
1. WhatisInheritance?
2. WhataretypesofInheritance?
3. WhatisExceptionhandling?
4. Whatare trycatchblockofexceptionhandling?
AssignmentNo:4
Title:
Filehandling
Objectives:Tolearnconceptof filehandling.
Theory:
Stream:
Astreamisasequenceofbytes.It
actsassourcefromwhichtheinputdatacanbeobtainedor
asa destinationtowhichthe outputdatacanbe sent.
1.InputStream
Input Streams are used to hold input from a data producer, such as a keyboard, a
file, or anetwork. The source stream that provides data to the program is called
the input stream. Aprogram extracts the bytes from the input stream. In most cases
the standard input device isthekeyboard. Withthecinand“extraction”operator(>>)
itispossibletoreadinputfromthekeyboard.
2.OutputStream
Output Streams are used to hold output for a particular data consumer, such as a
monitor, afile, or a printer. The destination stream that receives data from the
program is called theoutput stream. A program inserts the bytes into an output
stream. By default, the standardoutput of a program points at the screen. So, with
the cout operator and the
“insertion”operator(<<)youcanprintamessageontothescreen.iostreamstandardlib
raryprovidescinandcoutmethodsforreadingfromstandardinputandwritingtostanda
rdoutput respectively.
Filehandlingprovidesthreenewdatatypes:
DataType Description
ofstream Thisdatatyperepresentoutputfilestreamandusedtocreatefilesand towrite
informationto files.
ifstream Thisdatatyperepresentinputfilestreamandusedtoreadinformationfromfiles.
fstream Thisdatatyperepresentfilestream,andhaveboththefunctinalityofofstreamand
ifstream. Soitcancreatefile,writeintofile,readfromfile.
ToperformfileprocessinginC++,headerfile
<iostream>and<fstream>mustbe includedinyourC++sourcefile.
OpeningaFile
1. Afilemustbeopenedbeforeyoucanreadfromitorwritetoit.
2. Eithertheofstreamorfstreamobjectmaybeusedtoopenafilefor
writingandifstreamobjectisusedtoopena fileforreadingpurposeonly.
3. Followingisthestandardsyntaxforopen()functionwhichisamemberoffstream,ifstreamand
ofstreamobjects.
voidopen(constchar*filename,ios::mode);
4. Here,thefirstargumentspecifiesthenameandlocationofthefiletobeopenedandthesecondar
gumentoftheopen()memberfunctiondefinesthemodeinwhichthefileshouldbe opened.
in Fileopenforreading:theinternalstreambuffersupportsinputoperations.
trunc Anycontentsthatexistedinthefilebeforeitisopenarediscarded.
● Youcancombinetwoormoreofthesevalues byORingthemtogether.
● For example, if you want to open a file in write mode and want to truncate it in case it
alreadyexists,following willbethesyntax:
ofstreamoutfile;
outfile.open("file.dat",ios::out|ios::trunc);
Similarway,youcanopenafileforreadingandwritingpurposeasfollows:
fstreamafile;
afile.open("file.dat",ios::out|ios::in);
ClosingaFile
● When a C++ program terminates it automatically closes flushes all the streams,
release all theallocatedmemoryand closealltheopenedfiles.
● It isalwaysagoodpracticethataprogrammershouldclose
alltheopenedfilesbeforeprogram termination.
● Following is the standard syntax for close() function, which is a member of
fstream, ifstream,andofstreamobjects.
voidclose();
WritingtoaFile
● WhiledoingC++programming,youwrite informationtoafile
fromyourprogramusingthe stream insertion operator (<<) just as you use that
operator to output information tothescreen.
file.write((char*)&V,sizeof(V));
ReadingfromaFile
You read information from a file into your program using the stream extraction
operator
● Theonlydifferenceisthatyouuseanifstreamorfstreamobjectinsteadofthecinob
ject.
file.read((char*)&V,sizeof(V));
● These functions take two arguments. The first is the address of the variable
V, and thesecondis thelengthofthatvariableinbytes.Theaddress
ofvariablemustbecasttotypechar*(i.epointer tocharacter type).
Algorithm:
1. Start
2. Createaclass
3. Definedatamembersrollnumberandname.
4. Defineaccept()totakenameandroll numberfromuser.
5. Definedisplay()todisplaytherecord.
7.Takealimit fromuserinnvariable.
8. Openthefileinoutmode,callaccept()totakerecordfromuser,thencallwrite()t
owritethatrecordintothefileand attheendclosethatfile.
9. Open the file in in mode, read the record from the file ,call display()
function to displaytherecord and attheend closethatfile.
10.Stop.
Input&Output:
Conclusion:
Hence,wehavestudiedconceptofFile handing
Questions:
1. Whatisfilehandling?
2. Whatarethedifferentbenefits offilehandling?
3. What isfstreamclass?
4. Howtocreateobjectoffsreamclass?
5. Explainthesyntax ofread()?
6. Explainthesyntaxofwrite()?
A
ssignmentNo:5
Title:-FunctionTemplate
ProblemStatement:-
ImplementafunctiontemplateselectionSort.Writeaprogramthatinputs,sorts and
outputsan integerarrayand afloat array.
Theory:
Templates:-
Templates are the foundation of generic programming, which involves writing
code in a waythatis independent of any particulartype.
A template is a blueprint or formula for creating a generic class or a function.
The librarycontainers like iterators and algorithms are examples of generic
programming and have beendeveloped using template concept. There is a single
definition of each container, such
asvector,butwecandefinemanydifferentkindsofvectorsfor
example,vector<int>orvector
<string>.
FunctionTemplate:
The general form of a template function definition is
shown here:template<class type>ret-typefunc-
name(parameterlist)
{
//body offunction
}
Here, type is a placeholder name for a data type used by the function. This name
can be usedwithinthe function definition.
ClassTemplate:
Just as we can define functionb templates, we can also define class templates.
The generalformof ageneric class declaration is shown here:
template<classtype>classclass-name
{
.
.}
Here, type is the placeholder type name, which will be specified when a class is
instantiated.You can definemorethan onegenericdata typeby using acomma-separated
list.
SelectionSort:
Howselectionsortworks?
Example
For the first position in the sorted list, the whole list is scanned sequentially. The first
positionwhere14 is storedpresently, wesearchthe whole list andfind that 10is the
lowestvalue.
So, we replace 14 with 10. After one iteration 10, which happens to be the
minimum value inthelist, appears in the first position of sorted list.
For the second position, where 33 is residing, we start scanning the rest of the
list in linearmanner.
After two iterations, two least values are positioned at the beginning in the
sorted manner.Thesame process is applied on therest ofthe items in thearray.
Pictorialdepictionofentiresortingprocessisasfollows:
Algorithm:
1. Start
2. DeclarethetemplateparameterT.
3. Definetemplate functionforselectionsort.
4. In main() Define two arrays, one for integer and another for float. and take
a input forboththearraysand callsorting function templateto sortthenumber.
5. Stop
Input:-
EnterChoice1
Enter no. of elements in an array 5
Enterelements in anarray
34
78
90
56
12
Output:-
SelectionSort
Menus
1. Sortingofintegerarray
2. Sortingoffloatarray
3. Exit
Array before sorting
34
78
90
56
12
Conclusion:
Hence,wehavestudiedconceptofFunctionTemplate.
Questions:
1. Whatistemplate?
2. WhatisFunctiontemplate?
3. WhatisClasstemplate?
4. Explaintemplatewithfunctionoverloading.
5. Explaintemplatewithnon-typeargument
A
ssignmentNo:6
Title: -PersonnelinformationsystemusingsortingandsearchingforSTL
andvectorcontainer.
ProblemStatement: -
WriteC++programusingSTLforsortingandsearchinguserdefinedrecordssuchasItemr
ecords(Itemcode,name, cost, quantityetc)usingvectorcontainer
Objectives:
TolearntheconceptSTL,searching,sortingandvector container.
Theory:
STL:
The Standard Template Library (STL) is a set of C++ template classes to
provide commonprogramming data structures and functions such as lists, stacks,
arrays, etc. It is a library ofcontainer classes, algorithms, and iterators. It is a
generalized library and so, its componentsare parameterized. A working
knowledge of template classes is a prerequisite for workingwith STL.
STLhasfourcomponents
● Algorithms
● Containers
● Functions
● Iterators
Algorithms
● Sorting
● Searching
● ImportantSTLAlgorithms
● UsefulArrayalgorithms
● PartitionOperations
● Numeric
Containers
● Containers or container classes store objects and data. There are in total seven
standard“first-class” container classes and three container adaptor classes and
only seven header filesthat
● Vector
● List
● Deque
● Arrays
● forward_list(IntroducedinC++11)
● ContainerAdaptors :provideadifferent interfaceforsequentialcontainers.
● Queue
● priority_queue
● stack
● unordered_multiset
● unordered_map
● unordered_multimap
Functions
The STL includes classes that overload the function call operator. Instances
of suchclasses are called function objects or functors. Functors allow the working of the
associatedfunctionto be customized with thehelpof parameters to bepassed.
Iterators
As the name suggests, iterators are used for working upon a sequence of
values.Theyarethe major featurethat allow generality inSTL.
Sorting
It is one of the most basic functions applied to data. It means arranging the data in a
particularfashion, which can be increasing or decreasing. There is a builtin function in C++
STL by thename of sort(). This function internally uses IntroSort. In more details it is
implemented usinghybrid ofQuickSort .
HeapSort and InsertionSort.By default, it uses QuickSort but if QuickSort is doing
unfairpartitioningandtakingmorethanN*logNtime,itswitchestoHeapSortandwhenthearraysi
zebecomesreally small,
Theprototypeforsortis:
sort(startaddress,endaddress)
startaddress:theaddressofthefirstelementofthe array
endaddress: the address of the next contiguous location of the last element of
thearray.
Soactuallysort()sortsin therangeof[startaddress,endaddress)
Searching:
It is a widely used searching algorithm that requires the array to be sorted before
search isapplied.Themainideabehind thisalgorithm is tokeep dividingthearray inhalf
(divideandconquer)until theelement is found, orall the elements areexhausted.
It works by comparing the middle item of the array with our target, if it
matches, it returnstrue otherwise if the middle term is greater than the target,
the search is performed in the leftsub-array.Ifthemiddleterm isless
thantarget,thesearchis performedin therightsub-array.
Algorithm:
1. Start.
2. Giveaheader filetouse‘vector’.
3. Createavectornaming‘personal_records’.
4. Initializevariablestostorename,birthdateandtelephonenumber.
5. Using iterator store as many records you want to store using predefined functions
aspush_back().
6. Createanothervector‘item_record’
7. Initializevariablestostoreitem code,itemname,quantityand cost.
8. Usingiteratorandpredefinedfunctionsstorethedata.
9. Usingpredefinedfunctionsort(),sortthedatastoredaccordingtouserrequirements.
10. Usingpredefinedfunctionsearch,searchtheelementfromthevectortheuserwantstoche
ck.
11. Displayand callthe functionsusing amenu.
12. End.
Input:
Personnelinformationsuchasname,DOB,telephonenumber.
Output:
Displaypersonnelinformationfromdatabase.Theresultinfollowingformat:
*****
Menu
*****
1. Insert
2. Display
3. Search
4. Sort
5. Delete
6. Exit
Enter ItemCost:50
EnterItemCode:1
Conclusion:
Hence, we have successfully studied the concept of STL(Standard
Template Library) and how itmakes many data structures easy. It briefs
about the predefined functions of STL and their usessuchasearch() and
sort().
Questions:
1. WhatisSTL?
2. Whatarefourcomponents ofSTL?
3. WhatisSorting?
4. WhatisSearching?
5. Whatvector container?
Assignment No:7
● Problem Statement: -
Write a program in C++ to use map associative container. The keyswill be the names of
states and the values will be the populations of the states. When theprogram runs, the
user is prompted to type the name of a state. The program then looks in themap,using
the state nameasan indexand returnsthepopulation ofthe state
● Objectives:
Tolearntheconceptof mapassociativecontainer
● Theory:
Mapassociativecontainer:
Map associative container are associative containers that store elements in a mapped
fashion.Each element has a key value and a mapped value. No two mapped values can
have same keyvalues.
Maps contain sorted key-value pair, in which each key is unique and cannot
bechanged,and itcan beinsertedor deleted butcannot bealtered.
● ForExample: -
🞂 Syntax
map<key_type,value_type>map_name;
Map<int,string>m1;
◦ This will create a map with key of type Key_type and value of
typevalue_type.
integermap<string,int>map1;
=400
MemberFunctionsofMap in C++STL
1. atand[ ]
The only difference between them is that at throws an exception if the accessed key is
not present inthe map,on the other hand operator [ ] inserts the key in the map if the
key is not present already inthe map.
2. empty,sizeand max_size
c) max_size() returns the upper bound of the entries that a map can contain
(maximum possibleentries)based on the memory allocated to the map.
3. Insert
insert() is used to insert entries in the map. Since keys are unique in a map, it first
checks thatwhetherthe given key isalready present in the mapor not,
if it is present the entry is not inserted in the map and the iterator to the existing
🞂 Therearetwovariationsofinsert():
a) insert(pair)
b) insert(start_itr,end_itr):
4. Find()
find()returnstheiterator totheentryhavingkeyequaltogivenkey(passed
asparameter).iterator=map_name.find(key)
or
constantiterator=map_name.find(key
Algorithm:
1. Start.
2. Giveaheader filetomapassociative container.
3. Insertstatesname&population ofthatstate.
4. UsepopulationMap.insert().
5. Displaythe populationofstates.
6. Enternameofstatefor search
7. Displaypopulation of that state
8. End.
Input:
Output: -
Enterstatename kerala
Enterpopulation345681
State Population
Bihar 3441123
Karnataka 3456810
Kerala 349498766
Maharashtra6543332
Punjab 459589869
Enterstate Kerala
Key-valuepairpresent:
Kerala->349498766
Conclusion:
Hence, we have successfully studied the concept of map associativecontainer
Questions:
1. Whatisanassociative containerinC++?
2. What is map in C++?
3. Howtododeclareamap?
4. ExplainAssociativemappingwithexample?