Endsem Paper 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Total No.

of Questions : 8]
SEAT No. :
PB3635 [Total No. of Pages :3
|6261}-42
S.E. (Computer Engincering)(Computer Science &Design
Engineering)/(Al&DS)
OBJECTORIENTED PROGRAMMING
(2019 Patern) (Semester - III) (210243)
Time: 2½ Hours) /Max. Marks: 70
Instructions to the candidates:
1) Answer 0.7or 0.2, 0.3 or Q.4 0.5 or Q.6, Q.7. or Q.8.
2) Draw Neat und Clean Diagram.
3) Assune Suitable data, if necessary.
4) Figures of the rights indicate full marks.
Q1) a) Explain need of operator overloading. What are the rules to be followed
when overloading an operator in C++?
b) How virtual functions are implemented in C+? Explain with help of a
program. [6]
c) Define a class string and use binary overloaded operator (= =) to compare
two strings. [6]
OR

02) a) What is abstract base class in polymorphism? Explain with program.


[5)

b) Explain Virtual destructor with the helpof a program. l6]

c) Write C++ program to demonstrate use of unary operator (- -)


overloading using member function and unaryPOL
operator
2overloading
01 2 4 (t+)
using friend function. |6]

Explain the errror handling in file I/O. [5]


03) a)
and Using
b) Explain the two ways in which tiles can be opened, open ()
constructor with a program. |6]

c) What is stream? Explain types of strcam available in Ctt ie istream,


Ostream, ifstreanm and ofstream.
OR
PI0.
04) a) List and Explain different Mode bits used in open () function, while
opening a file. (Any five)

b) Explain the command line argument in C++ Write aprogram to explan


the samne. [6]

c) Which header fle do we use for file handling? Explain the following file
handling functions
3 7static-238
31
seekg
ijiellg)
in) Soekp () 13091
tellp ()

exception in
05) a) What is exception in C++?Explain each keyword to handle
C++.

What is template function? Explain with suitable example.


[6
b)
class templeate
c) Explain class template. Write a program to demonstrate
in C++.

OR

program for the


06) a) What do you mean by rethrowing exceptions. Writea
same.

implemented in C+t, [6]


b) What is generic programming? How it is

c Write a program in C++ to demonstrate cBass type exception handling in


[6]
C++.

2
|6261|-42
Q7) a) What are the various algorithms available in STL?
C++ program. Explain any one with
b) Write a programto implement map in C++. [6]
c) What is acontainer? Whatarevarious types of containers? Explainany
twocontainers in details. [7]
OR
Q8) a) What is the algorithn in STL? Explain sort function with example. (5|
b) What isasequential container? List various sequential containers.
Corjpare artays and vectors. [6]
c) 49.248.216.
What is iterator? Write a program in C++ to demonstrate the use iterator.
I7]

CEGPÖ#

248.21

PO13091

3
|6261|-42
M T WTF SS
|Page No.
YOUVA
Date:

EndSem - Object OientAed Proqramming


Mark8-70
Explan need of operator ovenloadung. ohat
the wles to be tollDuutd ohen ovLload'ng
an opeIator n Ctt

Opeuatos ovêxLpading is a featune in ctt that


alloYogrammer toJude7ine the benavior of
opeMator9 ohen 0orkung oith use dekined data
types, Such a Casses or SEructs

Need of Opeuator Oveuloading


1: Tncreased expregsiveneSS OpeHator oveuloadig
alloos tor moe natural and expresSive codng
2. TmprOved Yeadability Opeato mo nake code
Rasien to undeMStand and naintain

3 Enbanced usoiity : Dpeuators can make useudefin


ed types more intuitive t oonk oith
Rules tD kolloo ushen oveuloading an DpMator n

Only oveload Opeuatnthat make Sense tor


youH class
2 folloo the opeatoris oiqinal semantid
3 Be consistnt uoith the built- n typeS
4 Avoid overloading opeatts uoith ci ttthent
mmngs
Page No

Date
YoUVA
5. USe constconectness
6. Consid non-membeH tuntions tb Symmebir
opeuatong
7. Desine oveloaded operatrs as membeu t
on-mermbu tuntiomS, but not both guni
8- Be auoas of opeatr preeduna and a ssocok:
q: Test youH oveloadud o patot thotoughy
b) Ho rirtual tunctiong implementtd ulu
Explain oith help of a proqram
Enabling virtual tuntions
Huntime poynmrphiSm, oheu the onret
7untion to colu s deteAmi Ned at runtime rathuy
than compile time tte's a Simplicied
explanati om bf hoLo virtual tuntions
mpleenttd n Ctt.

Vtoble Fach lage Loith irtual funtions


a rirtual tabu Cvtable) that StoreA poinths to
ts itua tuntio

2 Vptr: Each object of the das contauns


yirtual pounte Cuptn that points to thu Vtalt
8- function oenidig ve claseA can ovedi.
Deivedl
Dei
virtual tuntiond, anc thei Vtasts te updatud
acordingy
L funtien al: Dhen.a vi tual *nction u
Callac the vptr u uyed to tind the comtet
kuntim to Lal:
W

Page N
YOUVA
Date

Hes an example proqram that demonStratas


nrtua tunctions

# incul <ioshea m)
USing amespae Std i
clas Shape 9
public
vìntual void olHa C)= 0

Clau Circu : putic Sh¡pe 9


public:
Void duauo C) ovehide
cout < Draounq a hce <<enodly

dlas Rectangle i public Shape


Void olao ( oveidle
cout <<" rauing a nectangli<(end;

pbtic

int maun c S
Shape *Shape I = neuo ircle c);
Shapt * Shape 2 a neo RectangLé ();
|Date:
vOUVA
Shape l ’ drauo C);
Shape2 -) drauo);

delte shape
dulte Shape 2)

3
c) Degine clags Sbinq and uae binauy ove
opeHato CE=)to Compe huo Sbrings

’ Heu u an examplu ot a Sting dus witha


binay ovebacud == 0peuatoo to ompautuÙ
Strings
# incuce Kiogbream)
tts using namelpaca Std j

class S tnng
ivate
chan* data
int length ’

tength = ghrlen Cstr)


data nenchaH Clength t1J}
Strcpy (data,Str)

Sting ()
delite [ clata
M TF
Page No.
YOUVA
Data

bool opator ==(onst Stinq othe) ongt


Htn Str cmp Cdata, oth-data)=0

fritnd.o Shrea md opeuator <rCoshream &os,


conSt Shing2 st)s
og<< Sbr. data y

int main )
Sting Str| ("Hello"),
Shing Str 2 ("tHelo")
Sbing Sttr 3 (" World "ý
Out < "Strl
Cout K'str2:" <<Str2 <<endL
Cout <<"Str 3i" <<str3 <<end

cout c" Strl and gtr2 e eaual"'<<endl


ele
Stt owt <"Stri and Shr2 aue not equalk
end Ly
outKgrtanot
if CSt= = Str 3)
Cout <'" Stol ano tr3 asu eQual ? <Kend',

(D ut <<"Strl and str 3 ate not equel'<


end Li
Date

YOUVA
abStra ct baße dasn C++
Q:2 a) What is
Explain with proqram

’ An abstract bas clag8(ABC) nCtt u


that Caonot ebe iStaniated on ts own and
cdesiqned to be inhuted by Otnn classes. Te
pwu virtuol
typicaly contain at least one dulad
tun tion, ohich is a tuntiom uith
indica t..
the =o Suntax at the end ThiS
that ans d i ved cass muLst implement thi
bunctin

Droguam:

USing namespaa Std


cdass Shape
putic:
4
irtual void duauo )= o;
das Grcu : putic Shape 9
putic i
Void dauo () 0vehhide
Cout <<" Drauong aircle'". <K cnd lj

daw Rectange : public ShapeS


pubtic :
Void duao () Dversidu
cot <<" Drouoing a iect
ectang
S S
Page No
YOUVA
Date

int man C)S


Shape * Shapel = neoCirce )y
Shap * Shape 22 neo Rectang le ()
Shape I-) drao C)
Shape 2-) draol)
dute shapt y
dulete Shape 2

TO hiS eAanple i
Shape u the abgract base clas uith a pute
irtia tunction duauwc
Gruee y Rectangle a ducied clasSeg that
inheit 7rom Shape and inplement the dla
Int man c ue cLat obËlets of ircle and
Rectonge and Call the cua O kunction
throuqh a Shape pountu
The coret duau O kun ction ijis calld ct
wuntie based on the objects tupe,
dernongtrating polymphism
Page No

Date:

YouVA
dusbructo oitth the
6) Ex plain Virtual
a proqram

destru tor is a destrutor


’A vixtua
is declaud Dith the virtual KeyooTd that
oth in
hat tthe Cnyect
base class. St engues dut
u calld ohen deletng an objtct 0f of a duk
duiy
do
class thiough a ponte to the base

Program
+inlude <i 0Shreann)
USìng nameßpace st

class base
pubiC:
Base C)
COut (K "Bae congt u t z Cald'k
endlif
Cot <r "Base destucto7 (alled (endl

claßs Deived : public Base


pwbic:
Dei ved (0
Out <K"Deived (o0ghutox
Calld KendLy
Coalld!
lout << ^ Deived destuct2
M T F S

Page No.
YOUVA
Date

intman )§
Bage x baße ne Deuived C)
dete o bae

Bae e conshutor calleol


Deuivtd contruct Called
Base destructY Cailed
Deuiveddstuc toy Cald
Ctt.
uny opeaton (-)oveLo ading usng
membe funcion and unasy opuator
oveHloaong (tt) ung fiend gunction
’ Pro qram
# indude<iostream)
U3ing namespace Std
dass ount
piratL
int cont
public:
CounteH 0: 0unt Co)?

Counta optuatY-0
COunt
etLO this.
Page No.:

Date:
OUVA
fiend Counteu opetatrt+ (ounters

3 int ger Cownt() Const


utus count ;

int main )
Count
cout<<" nibial count:" <<-getlount)ecd
Cout <<" Count attt --;"<KCqetlount)«er
Cout (< " Count att t+:<<cqet Dunt)kendl

0/P :
mitia count ! 0
(Dunt a t t t - - -J

In thi pooram, we have a Counte ca


oith a mvat ount membe vaiaee
ovewload the unauy -- opHt Usn
memb tunction optato--) which
ducnents tthe count vauii. u0e also
Dveload the unay tt
Unuy +t o peuato usng
tend tuntion opator + t (lounte c),
Lohich inlements the Count Vaiatl
aqe No
YOUVA
Date

Noto that the 0peuator - ) mnermbeu kuntti


HutwnS a ue7unce to the hnt objet
( this) to alo chainng bt Opthations.
he ophatoott (Coun tehec) thend tuncion
also utunn ahethne to the moditied
obect Cc) ttn the Samu taon

Q3 a) Explain the.eor handling in file Ilo.


’ Emon handing n sile I/o u ucial to
engwe that yoA proguam can hand le
uêxpeCtEd Si tuation, Such asi
File not tound
2. Peuigsion dunied
3: DiSk tull
4: Fle cOmupto
S Unexpecttd eod o7 tile
teue ae Some ways to handle eOrsn

1 ChecK file nopen Statui Abt apeNng


tu, check Lt thebile u SucceSStulls
Lopened by cheeKng the 7ile ponttu ox Sha
SAat

2- USe try- catch blocks - ÜTap tile I<o opevattion


in try- catch block3 to catch exceptioni tthbon
by the tile I<D kuntons
3 ChecK. eshr tlag Many file I|o functiong
Date:

YOUWA
checked
Set 7lags that Can be attu
opeuati on
Some klu I/o chunctions u
Checked to
Cod that Can be
detenMìne
b) Explain the t o ways'n ohich les can be
opened, open () and Using onstuctr uoith q

>In Ctt, ti les can bt opened n t00 oays:


1 USung he open () tuntion.
The open -¬) un ction ss amembeu of the
{stream das Cand it oeuived clases'ushean.
0fstream, and fsteam) Tt opens a ile and
a9Sociates toith the sham obect
2: USi0g the constutos
The constructor of the fsfam clas Cand ts
dived daes) Can o Le ued to oDn a tl
Thi
(ombines the ntion k the Strtam obËect a
the opening of the tìle nto a Single Statemesb
Heu's a proqram that demongtatu both ay
+iudu <ioStream)
tt incude <fsream)
USing namespau Gtol
int monl)
T W T F S S

Page No.:
YOUVA
Date:

LfSheam ALeL
filel open ("example.tat")
iE CAleL is-open0)S
cOut K"Ale opeñed
Dpen) kunction "" Sucess7ully
s ng
< endl

<<"Eno openunq tile wng


uing openy
tunhon endlj
iESheam ile2 (^enample -txt" )}
iECeile2. isopen ())3
C0 ut <"Ale opened Successtulliy wng
(ongbuctur" << endL
else
Cons
Dpening <<end
ucto.
file uing
L;

fle2.cloße c

this pooqram, we open a tetle na med


"eKampletatng both the open C) tunion
the constructo we tnen checK it the tile u
Succes tully opened usng open ()
tuntiop
Date:

of Stream
ExpLaun types oSbream
what s Sbreamm iie 1sStrtam,
availate i n c+t
and ofSbream tshrtan,
abstractionthat
epresents a How of clata JEs a uau
or
ead o7 Lorite data to a device, bi le,
Stream9 provdle a convioient and tle
luttey opeuations
uy to handle input /Dutput
Theu aue seveal types of Stbrtams availaHe in

LStyeam- Jnpt Sbtam, Used tor readng data


trom a Source, Such as Standaud input ies,
0r memOry Iutter
2 0steam - Output Stream, used tox oriting da
to a destination, Such as StandaHd output s,
memos butteru

3. isbeam- Ioput jle Steam, deAived ronm


iSbream, Speuficaly desined tox reading rom
tile
4:0fStream- O utput tile Streom,douved grom
D3brtam Speutuay desiqned gor oriting
ti les

These steams proide a vauetå of mnembel


Such
tuntions t veading and oiting data,
MTwT

Page No
YOUVA
Date

eadc, ontel, qetline C1 ,qetO put O,<<,


Ptc
Using sreams Simpliies input output opeuations
and povides a high: level in teukace to Øokung oit
data

Q:4 a) St and Explaun ditternt Modle bi ts wtodusd


in open ) tunction, ohi Le openng a ti le lAnys)
He e 7ive mode bit ued in the open()
7unction while opening acile
1) iS:n - open the 7ile tor neading This moda
bt alUoug you to tacd data i krom the tile
Open the tile tY Loitng Thìs mDd
bit alo you to ntedata to thetile

3) 109 apprpen the tile in append mod This.


mode bit a O you to apptnd data to the
end of the tile oithout oueoiting existung
data.

4) ios :: ate - Open the tile and move the ile pointt
to the end ofthe kìe This mode Ght allows
yDu toStart unding on mtng rom the end
of the tile.

s) ios :: trun Open the bile. and truncai t


content9 Thi9 mode bit dlo g you to delete the
exting-tontnt of the fle anc Staat U0iting
tiom the beqinning
M T

Page No.:

Date:
YOUVA

Cexanmple txt. ios:: n|ìos:: ouli


file ope0
trunc) i o both
This opens the te "exampletxt"
eacling and oitng, truntalu ts contents and
from the
alooyou to Stt ntng from eginai
ne augument
Q.4 b) Explaun the comma no
Ct+Wit a proga to eaplaun the samu
’ Command ine aquments ae s pasa
to a ctt protM can t proqam ohen ta
executed rom thu command n They
aqumunt a wsed to provide input to thi
pro qram without modityng the SowHe codi
Syntax
The main tunction ün C++ Can taKe tu
pauamte:

int maiun (int agc, cha ang L])


1| proq7a mcodl
qc Chgumnt o unt): Thu numnot
ommand unu aqwments pused
gve Prg ument vector): An aHay O8
characRH pontts contauni ng the a
quments
W S S
Page No
YOUVA
Date

Example
0n te aCtt program that takes too inegs
as connmand une augumerde and én calculote
th Sum

Son:
#/ncde<ioShreaum
USing name Space Std
int man Cint auge chay * auqv DO)
cout <<" US ag << aNgvto]<c'Knuny
<num 2) "" << end li

int numl = Sto/ (awgv 4] ;

int num2Stoi Ong vC21;


int Sum : n um t num2;
cot <" Sum: «Sum «endLi

Ex planati on
Check Lt the numbu0 qnunts( ugc)
y a 3C proqzom nome t 2num bes)
2Conveut the Sing g
M

Page No:

Date:
YOUVA

aHqv C2] ) to inteqes usung StoL


g Calaati th Sum
:l Pint th UHSlt

Sum: 12

Which headu tilu do we w t07 tlu


handling ? Explain the toloing tilu
i) seek C)

iv) lp ()
Headou RLe to fle Handlig
un thu tollo urng huadu7ils

+ indud <FSheam)
# iodwudaiohêam)

in put Dutput opeHations, uhile iostre am)


paovids input output tunctiona tor consolL
opetatioTu

Hle ttanding fünctions


He ue explaunio fo 4he tile handlng
kunction you usteol:
M T W T
Page No.
YOUVA
Date

4 Seek ()
Seekg () Sets the ioput position iadicatr to
Speci sied Location in the ti le

iSheam Beek (streampoS po3);


Doua metes.
pos: The position to Set the input po tión Ëndicaboz

Examplas
if shream file C" example -txt")j
ile See K Cio)/set input poibon to lo +th chaactue
2 tellq()
tella () tuni the cuot input position
inddcator
Sheampo tellg );
Retn va
. The cunnt input po githon

Example
if Stream tile C"exampety t") ;
tile sedk C10) ;
wut <<ile. tellq C) <r end l; lD]P o
3: geeKp()
Seekp () sets the output posi i n indi ator
to a Spei7ieo ocation in the tile
oStreo.n qeckp (steampos p0 3)
M T W

Page No..

Date:

Patame
pos:The.po8i ion to 8et th output no
indlcato
Example
("exam pletxt"j
tile. Seakp Zio); 8et oiutput positio t
|D th chauaH

4 tellp)
telp C) tu the cwnt output poßitig
incicatos
SheampOs telp() j

Thia n t utput p0SItion


Exgte Example
otSheam tile C"exa mpla tt)
tiu 3eek p Cio)j
M T W T

Page No.:
YOUVA
Date

Q5 ) hat n Ctt 2 Explaun


S eXcpbion
each Key uoTd to handle excptian n C tt
’ InCtt, an exception an event that Ocw
duuing the exeCution og a proqTam,
diuuping the mooml tlou agR ingtructions
Excption can be

2. hogic ehs
Syate ehhd

Exception ttanling KeywoTols in Ctt


lo hanle excapions, Ct+ poicles thu toLlo
keyoords

trË blockg encln se coole that might thoo an


eYcption

try that night tYo an ex caption

2: catch
catch blocks handie exceptins throLn by tha
try bloCK

" 0d that might thw eun eX Cap tion


catch (excaphion type e)
exceptÚn
uate
YOUVA

3:thOL
throo Stattments. expidty Hhro aan

ex caption
throw eKcptionobject
4: tho
e thoo Statments -thro o thu cwhns
excLption
Catcn C:)
1| Handl the exapion
etho0 Re-thsoo the exCeption

no encapt
noexcapt SpeiHel that a tuntin does

Void tunction mmnoexcapt


|/ Auncti on cooa

b ohat iu template tuntien 2? ELplain uolth


guitou example
Ternpl at tunction au a teatuu og Ctt
that alus uou to nite qenec tunctiors
that can oork uoith d kttthunt data ty pes
Thay enase codi t e and tle xi biby
T W

Page No.
YOUVA
Date:

TRmplate tunhans hlp :


1 Ayotccod dupication.
Shmprov code tuxi bility

Syntax:
tmpladL < typename T)
t n - type tunchan- name paamty
List ) 9 / Funcian bD dy

hypenane T : clecau o type panametT.


etnt ypt Speies the tunciion tun
by pe
huncim- nam uthe Aame 0t the tunctin
panmut list Speigìes thu kun tiis paHan
Example : Ancing Manimum alu
* indud <iaghreamyusing namespau Std
emplat <typenaume T >
Paqe No.

Date:
YOUVA

int man ()9 C]=3L,5,3,9,°;


int int A
1)
!
but " max iot v e
5)<tndl
cOut <"max doue va:"<<incl ManldoJ

fMax int a e 9
Man dowre val9.g
templat Weite

’ la Templatis in Ctt
las templ ats
allbs you to Cate gunic cdases tht
can oork otth dittnt data bypts They
ene enates cod1 eeu and tuxibii6y
Heups
: vod nd dupication
2: mon codu kuxibiit
progming
Page Na
YOUVA
Date

Syntax :
templatu <typename T)
Clascloss Dame
WAAcUs dakiniton

Example Prognam
Unq namespae. Bbod
tumplat <hypename T)
dass
poivat
T ond
putic
I/ Consuctor
Pain' (ITE,TS) hst Ct), Second (9)2
J| Cett tnctiond
get rst () connst
T get Seond () const
/ Seter tunctianu
tio.
Void Strst (T f)tirs t =tjf
void set Sewnd(T3) Beondl = S
M

Page No.:

Date
YOUVA

int main () Pain objecd1 tus duittehs


Jl Cuuat
Paih int) intPair (5,10); 3,5,1,8
Pain <do ute dloePainA2):7
Pai <chau chnPauh
| Acces and Modiks
modiby als.

Cout cSot Pain:"intPain getiast)


int Pai at Scconol) <c)'<end L;
int Paet Sst (0)j

out << "Updatd oubta Piun :("<dotai


qet rst () <<"," <<_ds
Dut << " Ubdatd Sot Pan: (" <<
intPain ge LArst ) cc", << intfai
qet Second)<"y" <Cendl;

cout <<" Daubte Paçn : ('<<co ePan.


Poi.Qutfst
(<","<K doubta Paun .at SecondlCS
dowte Pauh etSe cond Cg.9):
CDut < Updoted Doue Paun
("<K dowalain getsecono C) <c)'qendl
M

Paqe No
YOUVA
Date

Chaufaun. Set fs t x)
out<<"Updateo Chas Pais: <KcharPain
qet Finst cy<<,"Z char Pan qetSecondl ()c
"Kstd endL;

DP:
Sht PouniCs,lo)
Updated Jnt Paus : C2o,lo)
Doue Pon: C3:5,7-8 )
Updated Dotte PainC3:S,9.q)
Cha Pain : (Az)
Upd cted Chau Pais Cx,2)
Q4)Ohaf do you mean Dy ethroüng
eXceptions wite a moqram to the game.
’Rerhro uing exception is a technique used
in excption handling oh an excption
Caught procasAld , and then t- thtoon
to be badled by anotheu excaption handl lca,
Lohy Rethrow EXceptions322
1 Additionad proessg : Petom addition al
tasks betone e-thtowing
2. Logginq Log the excptien to aucli ting r
duq ng
9 NotikicatiÝn - Notity othut parts o% th syst
Date.

about the ex ception AUohiqh-


4HieHUnchical hanoling
Ahe excption
t hand lahs to manag
n
Output Progoam
# indude <ioghream
# incude <Stdexcapt
Uginq na megpae Btol ;
do diida Cdoe num , dlowunm
it num 2= =0) S
thoo Std: muntimeego
Division by zuw);
Uutu um / m2
int main )g
diile Ci0, o)
R catch Cconst Std?: excaptionke).
out << "Caught excp ion:"<K
p Lohat ()<<endll

Caught exception: insio by zeo


teminau callad agtuy thuowinq an
Page to
YOUVA
Date

nstane oh 9tiuntimeer

b) tohat u geneic prOqtaming 2Houo t iu


implementtd n Ctt.

Genuic programmng
pauadiqm that allos ontina pde thdt
Can uork with oli ktent dafa typs
uoithout the need tur expliit type casting
6r 3epaat implementatiG bu each hypt

Ctt poOvidas Sevud uays to implement


qtneic programmng
|: Termnplates
Templatu e the pìmay mechanism
alouo cetiniDq tunctians and classeA that
Can uork oith ditternt datoa types.
function Template Example
te mplau <typen ame T)
Tmax (Ta,Tb)
hetn Ca)b) 2 a:b

int e t | max (5,10),


doutto eut2s Max C3,5,7,2);
tetno
M T W TF
Page No.:

Date:
YOUWA
21 Opeuato Oveladung
Opeuaty overlogdLng alous ditinn
behaior to opuatos whenJ
Custum
Custom Lehaio
u0TKing oith 5dutned ty ps
3. Type Trat absut
Type traits poiou intomnationqennic
tupes at compile- time , ena
(oole to make decisions bUsea om tus
propeties

CSulsitution failue Not an


Enor)
SE TNA¬ u a techniq,e wsea t Belca w
On type traiti
C) t a program n c++ to demon hat
Uass typeexeption handng in (4t.

Proram,
# incude(io3heum>
# indude < tolex capt )
Uging namespa Stcl ;
las DiideBy 2euD ExCaptiem: pulti c
Std :: untimu ero
puc
Dì vidaby Zoxo Er cephon (conSt cha
messogl):
M
T WTF S S
Page No,
YOUVA
Date

pic:
do ubte cide cdotenun, dorte
num 2

utn pum um 2

Calcuato éalcul ator:


ty Calculatodiviole C10,0 )
Rcatch Cconst DirioaBy2enoÉxCapbone)s
Sto:: co Keu"EXcaption aught:ewat(
endl

Dutput
Excsptian (augbt Diisian lby zeo d
not alowed
W

Page No

Date

YOUVA
+he vaiOw alyoith
Q7 a) ohat aue STL 2 bxplan tny on
avalattu

hitu
’ The Stardaud Templab alqoithm8CSTL)
aous to
Ct+ provdes Heu n.
Manipwatng ata Shuctus
Cattanes and examples Os ST L
Some
alqoithms:
Jtorati w Alqoithm
-each
2 unst0m

Soring Algoithms
1 Sort
2 StateS00t
3: artial &ot

Se asching Algonttama
2- nd it

Meging Algon hm.

2
3: mergnpn
t
Set o BCchion
YOUVA
|Oata

C+t Prog am: Sontung an Array usng


STL'S Sort Alqoithm.
+inud <ioghean)
* ineduoe Kalgomthmy
USinq namespaCa gtoli
int man c)
int ann[J : 3 5,2, 8,l,9
int n SËzeòs Carn) Si24 63 Carnlo)
0ig'na Aray
toT Cintiz 0; icoit t)

out <K endi


cout<<"Sorttod hry
kox (int is o; isoi+t)
0 ut Ka Ci]<<";

<<endl

O/P
Diginau Amay : 52819g .
Sorted hray
| Page No,:
Date:
YOUVA

a pr oq ram to impment man


b) wite
Ctt.

# inude <i og team)

* inducle <shing >


int
Stli:mapr"stol
Stod i:
i Stinq,int)
Agess
Studint Aaes C: Sobo"]= 20:
Stucnt Aaes [Aua
Aia"" 22
Studnt Ages ['"Bob"J= 213
Std i co ut <<''Map Etemens<<Stol:el
tor Cconat autl pas :StucuAge)
Std:; Out <<Map Eements;cstel:
to Congt autopan: Senstt uclun ty
Stod; Lout <pah kiost <<"<<a
Secon <<std ndli

Std i: ghring
3ing name "Ai

ShuclantA4es nama] <egtoleral li


else
YOUVA
Date

Std i: cout <<nam cenot tound "


S+di end li
StudntAq es C John"] = 25
Stol:: out <<"Updatd_ Aqe o7 ohn:
Studnt Ages Li John"<Std ::enolli
1

StuduntAgu: eOLe CBob");


Std: Dut K<"Map Eements atyduletin
<< Sto : end L
7or CcooSt auto pain :8tudent Ags)
Std: oit<c paskirt <K": "<<

Output
Map Ele nen ts
Aiee : 22
Bob :: 22|
John .

Aqe a H co 22
Updateod tqe o3 John : 25
map Elements astr deriSrletiam
Aice: 22
John: 25
T W F
Page No.:

Date:

a contaune What ae
types o Containuu 2 Explaun any
Contain er in detls

ootaun a contune Ua data Strud


Ctt
that Stores a coluction 0 0bjeti,
provding vaiow 0peuationd bor manin
and accÁang th elamets
ypes ot Contain ex
1 Sequen a Conteuins
Vector
Ust
Deque
- mry
fomaMd ist

2 Asso Ciativ e Containe


Set
Mliset
- Map
- Mui map

Stack
Prriomty ue
YOUVA
Date

Detailed Explanation of Too Containeu.


4 VectDY Containey

Vecto
A dynamie @ay-ike contaun that
can qroo o7 Shiok n si ze
Element3
menoy
Pooide st random acess,ins eutim
and dltion
Vector Opeatiom
push back ( : Ad dsg element at th end
iO Set CO: tete elent at a gpecisied
positbion
Ramoei met at a Speified
position

# indude <u etoUging namespQce Stl;


int mun C)
vector<int) vec= 2 , 3 ;
Vec.push bak (4);
cout< vec Co] <r endl;/|o/P: 1
Page No.:

Date

2. Set Contaunw
Set 0rdeLol contaún thatSt
An
elumurts
Etemetu a
tast lokup, insertian
Proile
dtlhon:
Set opeHations
i n g e ) n t a unique elnent
tind

tt iludls <Ret
U3ing namespac SHd CO:
Set<int>s =31, 2,3
Sinst (4);
cout <<"Elemnt tounal en dl

98 a) UOhat is the aqonthm n STL2


Explaun Soot fun tion usith exam pu'
’ Al¡orithms in STL.
The Standaud Te mplat Kibray CSTL)
provdes
korr nani plainq data
ghuchg. Thus
al g thm3 atuncthons that peusO Om
3peikic opehatÛn on Contoinezi Such as
Pagt tio
YOUVA

Sprtung,Seauching,coun tng nd more


Sot uncion

The Soot bunction lu a Soting algsthm


tht Yeaanges elmsts n a containeH to
n ascnding orden

Uginq namespae Std ;


t incud <algonthm)
# include <vecto)
int man)
vector < nt) numbeui =5,2,&,, 93;
Cout <"Be7o Boating :
kor Cint nuM numbeHs

cot <<encdl

Sort Cnumb ers. be qin ( , Dumbers.


enal ()]:
Cint num :Dumbers) S

Cout << enel

o/p Besre Botng: 528 19


Atte Sortin9 | 2589
M

Page N0:
Date:

Seqntial conttaun
Q8b) What u a contanwy
vaious eanial
and ve tos
and anays
Con tauneS is a
Sequê nbial contaunens
H souen'al
(omp contaune n c+* that 3tor
elument in a uneat eanl,aln.
elument:
acces and maoiplation Dk
a gpeci hic odin

Ty pes B SegLn tial ContuneHs.


.

2: Vecto

4 Deq d
6 StacK LLFO

Vectos
0 Axed at comple- oynamic, Can
ti me

(2 Static or automiatic2 Dynamic Mimy


alocation
3) Acces - Random accea Ranlen acces ui
wsing induing. indax n9
Not upportt d Suppoteod
push ba cr,ws
inse
S S
Faqe No
YOUVA
Date

Not Suppoated 6 Suppcnttd wslng


tox Rgi 2ig eei22
6) No built-n check 6)es, Using at tunh
Fastea acces 3ouh acce
Moitication StoWRL moi bi catiom d e to

lCation
ohat a jtenatr? ite
Ctt to denon brato the use itHato :

Steuato
An ite ato is an obiect that allows
eel braversal oeh a ontain es elments,
proiding acces to each elament oithat
expo Sing'the undiling implenentation
Proa rammi
U3ing namespac Sfolj
# incude <vector

vector <int)´nwmbs a I,2,3, 4,5


vetur <int>litehtor t

out <" foand traversalKendl:


korCit= numbs
it )3
Poge N

Date

Cout << endlj

*o (it= num bR end c - it


begin ),° -- jt)
btqint
cout << e n d i

tutuo
Out put i
Riwehst itraessal i5 43 2|

You might also like