0% found this document useful (0 votes)
2 views21 pages

STL_Notes

The document provides an overview of the Standard Template Library (STL) in C++, detailing its components such as containers, iterators, algorithms, and function objects (functors). It explains the benefits of using STL, including time-saving, reusability, and efficiency, and includes examples of various container types like vectors, lists, and maps. Additionally, it covers how algorithms operate on these containers and the role of iterators in accessing container elements.

Uploaded by

dikshakarna696
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

STL_Notes

The document provides an overview of the Standard Template Library (STL) in C++, detailing its components such as containers, iterators, algorithms, and function objects (functors). It explains the benefits of using STL, including time-saving, reusability, and efficiency, and includes examples of various container types like vectors, lists, and maps. Additionally, it covers how algorithms operate on these containers and the role of iterators in accessing container elements.

Uploaded by

dikshakarna696
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

StandardTemplateLibrary(STL)inC++

Topicscovered
IntroductiontoStandardTemplateLibrary
ComponentsofSTL
Container
Iterators
Algorithms
TableofContents
Tableof Contents.........................................................................................................................................2
IntroductiontoStandardTemplateLibrary(STL).......................................................................................3
ComponentsofSTL.................................................................................................................................5
1. Containers........................................................................................................................................5
2. Algorithms........................................................................................................................................5
3. Iterators...........................................................................................................................................5
4. FunctionObjects(Functors)...............................................................................................................5
Container...............................................................................................................................................7
A. SequenceContainers............................................................................................................................7
1. vector...............................................................................................................................................7
2. list....................................................................................................................................................8
3. deque...............................................................................................................................................8
B. AssociativeContainers........................................................................................................................10
1. set..................................................................................................................................................10
2. map................................................................................................................................................10
C. ContainerAdapters.............................................................................................................................12
1. stack...............................................................................................................................................12
2. queue.............................................................................................................................................12
3. priority_queue................................................................................................................................13
Iterators...............................................................................................................................................14
CategoriesofIterators.............................................................................................................................14
Algorithms...........................................................................................................................................17
CategoriesofAlgorithms.........................................................................................................................17
Summary....................................................................................................................................................21
ReviewQuestions.......................................................................................................................................21

(Right-clickthetableaboveandchoose“UpdateField”afteropeninginWordtopopulatepage numbers.)
IntroductiontoStandardTemplateLibrary(STL)
TheStandardTemplateLibrary(STL)isapowerfulsetofC++templateclassesandfunctionsthatprovide general-
purpose, reusable, and efficient implementations of common data structures and algorithms.
Insteadofwritingcodeforlinkedlists,stacks,searching,orsortingfromscratch,aprogrammercan simply use
the ready-made, well-tested components supplied by the STL.

STL is part of the C++ Standard Library and is built entirely using templates, which makes it type-
independent—thesamecontaineroralgorithmcanworkwithintegers,floating-pointnumbers,strings, or
user-defined objects without rewriting the code.

Definition
The Standard Template Library (STL) is a collection of generic classes and functions in C++ that
implementscommonlyuseddatastructures(containers)andalgorithms(searching,sorting,etc.) using the
concept of templates and iterators.

WhySTLisused:
● Savesdevelopmenttime—ready-made,testedcodeforcommontasks.
● Genericandreusable—workswithanydatatypethroughtemplates.
● Efficient—implementedwithoptimizedalgorithmsanddatastructures.
● Reducesbugs—noneedtore-implementstandarddatastructures.
● Encouragesconsistent,readable,andmaintainablecode.

AminimalexamplethatusesSTLcomponentstogether:

Program1:AfirstlookatSTL(vector+iterator+algorithm)

#include<iostream>
#include <vector> #include<algorithm>
//STLcontainer
//STLalgorithm

usingnamespacestd;

intmain(){
vector<int>numbers={40,10,30,20};//container

sort([Link](),[Link]()); //algorithm+iterators

cout<<"Sortednumbers:";
for(vector<int>::iteratorit=[Link]();it!=[Link]();++it) cout << *it <<"";// it
cout<<endl;

return0;

}
Output

Sortednumbers:10203040

NoticehowthreeSTLpiecescooperateintheprogramabove:thevector(container)storesdata,the iterator
(begin()/end()) moves through the data, and sort() (algorithm) processes the data.
ComponentsofSTL
TheSTLisbroadlyorganizedintofourmajorcomponentsthatworktogether:

Component Description
Containers Objectsthatstorecollectionsofdata(e.g.,vector,list,set,map).
Functionsthatperformoperationsondataheldincontainers(e.g.,sort, search,
Algorithms
copy).
Objectsthatactlikepointers,usedtotraversetheelementsofa container.
Iterators

Objectsthatbehavelikefunctions;usedtocustomizealgorithm behaviour
FunctionObjects(Functors)
(e.g., comparators).

1. Containers
Containers are objects that hold a collection of other objects (elements). STL provides three categories
ofcontainers:sequencecontainers(vector,list,deque,array),associativecontainers(set,map,multiset,
multimap), and container adapters (stack, queue, priority_queue). These are discussed in detail in
Section 8.5.2.

2. Algorithms
Algorithmsareindependent,genericfunctions(suchassort(),find(),reverse(),count())thatoperateon ranges
of elements specified by iterators, rather than on a specific container type. Because of this, the same
algorithm works on a vector, a list, or even a plain array. Discussed in detail in Section 8.5.4.

3. Iterators
Iteratorsareobjects(similartopointers)thatpointtoelementsinsideacontainerandallowalgorithms to move
through (traverse) those elements without needing to know the internal structure of the container.
Discussed in detail in Section 8.5.3.

4. FunctionObjects(Functors)
Afunctorisanobjectofaclassthatoverloadsoperator(),so [Link] algorithms
often accept functors (or lambda expressions) to customize their behaviour, for example, to sort in
descending order instead of ascending order.

Program2:Asimplefunctorusedwiththesort()algorithm

#include<iostream>
#include <vector> #include<algorithm> usingnamespacestd;

classDescending {

//afunctorclass
public:
booloperator()(inta,intb){
returna> b; //descendingorderrule
}
};

intmain(){
vector<int>v={5,1,4,2, 3};

sort([Link](), [Link](), Descending());

//functorpassedtoalgorithm

for (int x : v) cout << x <<"";


cout<<endl;
return 0;
Output

54321

Key Point
Containersstoredata,iteratorstraversedata,algorithmsprocessdata,andfunctorscustomizehow
algorithms behave — together these four components make STL flexible and generic.
Container
A container is anSTLclasstemplate that storesa collectionofobjectsof the same type. Containers
managethememoryusedbytheelementstheystoreandprovidememberfunctionstoaccessand
manipulate them. STL containers are divided into three categories:

Category Containers Description


SequenceContainers vector,list,deque,array Storeelementsinalinear,orderedsequence.
AssociativeContainers set,multiset,map,multimap Storeelementsinsortedorder,keyedforfastlookup.
Restricttheinterfaceofanunderlyingcontainerto give
ContainerAdapters stack,queue,priority_queue
special behaviour.

A. SequenceContainers
1. vector
[Link] using the []
operator and fast insertion/removal at the end.

Program3:Demonstratingvector

#include<iostream>
#include <vector> usingnamespacestd;

intmain(){
vector<int>v;
//emptyvector

v.push_back(10);
v.push_back(20); v.push_back(30);

cout<<"Vectorelements:";
for(inti=0;i<[Link]();i++) cout << v[i] <<"";
cout<<endl;

v.pop_back(); //removelastelement
cout<<"Afterpop_back,size="<<[Link]()<<endl;

return0;
}

Output

Vectorelements:102030
After pop_back, size = 2
2. list
[Link](O(1)),butrandomaccess is not
supported directly.

Program4:Demonstratinglist

#include<iostream>
#include <list> usingnamespacestd;

intmain(){
list<int>l={10,20,30};

l.push_front(5); //insertatthebeginning
l.push_back(40); //insertatthe end

cout<<"Listelements:";
for(intx:l)cout<<x<<""; cout << endl;

return0;

Output

Listelements:510203040

3. deque
Adeque(double-endedqueue)allowsfastinsertionanddeletionatboththefrontandtheback,along with
random access using the [] operator.

Program5:Demonstratingdeque

#include
<iostream>
#include <deque>
usingnamespacestd;

intmain(){
deque<int>dq;

dq.push_back(10
);
dq.push_front(5
);
dq.push_back(20
);

cout<<"Dequeelements:";
for(intx:dq)cout<<x<<""; cout <<
endl;
Output

Dequeelements:51020
B. AssociativeContainers
1. set
[Link].

Program6:Demonstratingset

#include<iostream>
#include <set>
usingnamespacestd;

intmain(){
set<int>s;

[Link](30);
[Link](10);
[Link](20);
[Link](10); //duplicate-ignored

cout<<"Setelements(sorted,unique):"; for
(int x : s) cout << x <<"";
cout<<endl;

return0;
}

Output

Setelements(sorted,unique):102030

2. map
Amapstoreselementsaskey-valuepairs,[Link] fastlookupofavaluebyits key.

Program7:Demonstratingmap

#include
<iostream>
#include <map>
#include <string>
usingnamespacestd;

intmain(){
map<string,int>marks;

marks["Ram"]=85;
marks["Sita"]=92;
marks["Hari"]=78;

cout<<"Studentmarks:"<<endl; for
(auto &p : marks)
cout<<[Link]<<"->"<<[Link]<<endl;
return0;
}

Output

Studentmarks:
Hari -> 78
Ram-> 85
Sita-> 92

Note
mapkeysareautomaticallykeptinsortedorder(here,alphabetically),whichiswhy“Hari”appears first even
though it was inserted last.
C. ContainerAdapters
1. stack
AstackfollowsLast-In-First-Out(LIFO)[Link].

Program8:Demonstratingstack

#include
<iostream>
#include <stack>
usingnamespacestd;

intmain(){
stack<int>st;

[Link](10);
[Link](20);
[Link](30);

cout<<"Stack(toptobottom):";
while (![Link]()) {
cout<<[Link]()<<"";
[Link]();
}
cout<<endl;

return0;
}
Output

Stack(toptobottom):302010

2. queue
AqueuefollowsFirst-In-First-Out(FIFO)[Link] front.

Program9:Demonstratingqueue

#include
<iostream>
#include <queue>
usingnamespacestd;

intmain(){
queue<int>q;

[Link](10);
[Link](20);
[Link](30);

cout<<"Queue(fronttoback):";
while (![Link]()) {
cout<<[Link]()<<"";
[Link]();
}
cout<<endl;

return0;
}

Output

Queue(fronttoback):102030

3. priority_queue
Apriority_queuealwayskeepsthelargest(bydefault)elementatthetop,regardlessofinsertionorder.

Program10:Demonstratingpriority_queue

#include
<iostream>
#include <queue>
usingnamespacestd;

intmain(){
priority_queue<int>pq;

[Link](10);
[Link](30);
[Link](20);

cout<<"Priorityqueue(highestfirst):";
while (![Link]()) {
cout<<[Link]()<<"";
[Link]();
}
cout<<endl;

return0;
}
Output

Priorityqueue(highestfirst):302010
Iterators
Aniteratorisanobjectthatbehaveslikeapointerandisusedtopointtoandmoveacrosstheelements stored in
an STL container. Iterators provide a uniform way to access container elements without exposing the
internal structure of the container, allowing the same algorithm to work with different container types.

EverySTLcontainerprovidesbegin()(pointingtothefirstelement)andend()(pointingtooneposition past the


last element), which are used to define a range for traversal or for passing to algorithms.

CategoriesofIterators
IteratorType Capability ExampleContainer
InputIterator Readelements,moveforwardonly(singlepass) istream_iterator
OutputIterator Writeelements,moveforwardonly(singlepass) ostream_iterator
ForwardIterator Read/write,moveforward,multi-pass forward_list
BidirectionalIterator Moveforwardandbackward list,set,map
Jumptoanyelementdirectly(likeanarray pointer)
RandomAccessIterator vector,deque,array

Program11:Usinganiteratortotraverseavector

#include
<iostream>
#include <vector>
usingnamespacestd;

intmain(){
vector<int>v={10,20,30,40};

cout<<"Forwardtraversal:";
for(vector<int>::iteratorit=[Link]();it!=[Link]();++it)
cout << *it <<""; // dereference iterator
cout<<endl;

return0;
}
Output

Forwardtraversal:10203040

Program12:Usingareverse_iterator

#include
<iostream>
#include <vector>
usingnamespacestd;
intmain(){
vector<int>v={10,20,30,40};

cout<<"Reversetraversal:";
for(vector<int>::reverse_iteratorit=[Link]();it!=[Link]();++it)
cout << *it <<"";
cout<<endl;

return0;
}

Output

Reversetraversal:40302010

Program13:Usingaconst_iterator(read-onlytraversal)

#include
<iostream>
#include <list>
usingnamespacestd;

intmain(){
list<int>l={1,2, 3};

for(list<int>::const_iteratorit=[Link]();it!=[Link]();++it)
{ cout << *it <<"";
//*it=100; //NOTallowed-const_iteratorisread-only
}
cout<<endl;

return0;
}
Output

123

Program14:Iteratingoveramap(key-valuepairs)

#include
<iostream>
#include <map>
#include <string>
usingnamespacestd;

intmain(){
map<string,int>age;
age["Anita"] = 20;
age["Bikash"]=22;

for(map<string,int>::iteratorit=[Link]();it!=[Link]();++it)
cout << it->first <<" is "<< it->second <<" years old"<<
endl;

return0;
Output

Anita is 20 years old


Bikashis22yearsold

Key Point
Useit->first/it->secondformapiterators(sinceeachelementisapair),and*itforothercontainers such as
vector, list, and set.
Algorithms
STL algorithms are generic, reusable functions defined in the <algorithm> header that perform
operationssuchassearching,sorting,counting,[Link] elements
specified by a pair of iterators [first, last) and are independent of the container type used.

CategoriesofAlgorithms
Category Purpose Examples
Non-modifying Inspectelementswithoutchangingthem find(),count(),for_each()
Modifying Changetheelementsortheirorder copy(),replace(),fill(),reverse()
Sorting Arrangeelementsinaspecificorder sort(),stable_sort()
Searching Locateelementsinasortedrange binary_search()
Numeric Performnumericcomputations accumulate(),iota()

Program15:sort()—arrangingelementsinascendingorder

#include <iostream>
#include <vector>
#include<algorithm>
usingnamespacestd;

intmain(){
vector<int>v={40,10,30,20};

sort([Link](), [Link]());

cout<<"Sorted:";
for(intx:v)cout<<x<<""; cout <<
endl;

return0;
}

Output

Sorted:10203040

Program16:find()—searchingforanelement

#include <iostream>
#include <vector>
#include<algorithm>
usingnamespacestd;

intmain(){
vector<int>v={5,10,15,20};
autoit=find([Link](),[Link](),15);

if(it!=[Link]())
cout<<"Elementfoundatposition:"<<([Link]())<<endl;
else
cout<<"Elementnotfound"<<endl;

return0;
}

Output

Elementfoundatposition: 2

Program17:for_each()—applyinganoperationtoeveryelement

#include <iostream>
#include <vector>
#include<algorithm>
usingnamespacestd;

voidsquare(intx){
cout<<x*x<<"";
}

intmain(){
vector<int>v={1,2,3, 4};

cout <<"Squares: ";


for_each([Link](),[Link](),square)
; cout << endl;

return0;
}

Output

Squares:149 16

Program18:reverse()—reversingtheorderofelements

#include <iostream>
#include <vector>
#include<algorithm>
usingnamespacestd;

intmain(){
vector<int>v={1,2,3,4, 5};

reverse([Link](),[Link]());

cout <<"Reversed: ";


for(intx:v)cout<<x<<""; cout <<
endl;
return0;
}

Output

Reversed:54321

Program19:count()—countingoccurrencesofavalue

#include <iostream>
#include <vector>
#include<algorithm>
usingnamespacestd;

intmain(){
vector<int> v = {1, 2, 2, 3, 2,

4};

intc=count([Link](),[Link](),2);

cout<<"Number2occurs"<<c<<"times"<<endl;

return0;
Output

Number2occurs3times

Program20:accumulate()—summingelements(numericalgorithm)

#include<iostream>
#include <vector> #include <numeric> usingnamespacestd;
//requiredforaccumulate

intmain(){
vector<int>v={10,20,30,40};
inttotal=accumulate([Link](),[Link](),0); cout<<"Sumofelements="<<total<<endl; return 0;
}

Output

Sumofelements=100
Program21:max_element()andmin_element()

#include <iostream>
#include <vector>
#include<algorithm>
usingnamespacestd;

intmain(){
vector<int>v={23,5,42,17,8};

cout<<"Maximum:"<<*max_element([Link](),[Link]())<<endl;
cout<<"Minimum:"<<*min_element([Link](),[Link]())<<endl;

return0;
}

Output

Maximum:42
Minimum:5

Key Point
STLalgorithmsneverworkoncontainersdirectly —theyworkonarangedefinedbyiterators(first, last). This
is what makes the same sort() or find() function usable on a vector, list, or plain C-style array.
Summary
● STL(StandardTemplateLibrary)providesready-made,generic,andefficientcontainersand
algorithms in C++.
● ThefourmaincomponentsofSTLare:Containers,Algorithms,Iterators,andFunctionObjects
(Functors).
● ContainersstoredataandaregroupedasSequence(vector,list,deque),Associative(set,map), and
Container Adapters (stack, queue, priority_queue).
● Iteratorsarepointer-likeobjectsusedtotraversecontainerelements;theycomeininput,
output, forward, bidirectional, and random-access categories.
● Algorithms(sort,find,reverse,count,accumulate,etc.)operateoniteratorrangesandwork
uniformly across different container types.

ReviewQuestions
● [Link]?Listitsmajor components.
● [Link].
● [Link]?Explainanythreecategoriesofiterators.
● [Link]++programtostorefiveintegersinavectorandprinttheminsortedorderusingSTL
algorithms.
● [Link].
● [Link]?HowisitusedtocustomizeanSTLalgorithm?Givean example.
● [Link] marks.

You might also like