SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Standard Template Library
Prepared By
- Sreejith S -
- Rahul Babu R -
Contents
 Introduction To STL
 Containers
 Iterators
Algorithms
 Function Objects
Introduction To STL
• STL is Standard Template Library
– Powerful, template-based components
• Containers: template data structures
• Iterators: like pointers, access elements of containers
• Algorithms: data manipulation, searching, sorting, etc.
– Object- oriented programming: reuse, reuse,
reuse
– Only an introduction to STL, a huge class library
STL components overview
• Data storage, data
access and algorithms
are separated
– Containers hold data
– Iterators access data
– Algorithms, function
objects manipulate data
– Allocators... allocate
data (mostly, we ignore
them)
Container Container
Algorithm
Container
Container
• A container is a way that stored data is
organized in memory, for example an array of
elements.
Container
Sequential Associative Container Adapters
Container ctd-
• Sequence containers
– vector
– deque
– list
• Associative containers
– set
– multiset
– map
– multimap
• Container adapters
– stack
– queue
Sequential Container
– vector<T> – dynamic array
• Offers random access, back insertion
• Should be your default choice, but choose wisely
• Backward compatible with C : &v[0] points to the first
element
– deque<T> – double-ended queue (usually array of
arrays)
• Offers random access, back and front insertion
• Slower than vectors, no C compatibility
– list<T> – 'traditional' doubly linked list
• Don't expect random access, you can insert anywhere
though
Some functions of vector class
-size()
-provides the number of elements
-push_back()
-appends an element to the end
-pop_back()
-Erases the last element
-begin()
-Provides reference to last element
-end()
-Provides reference to end of vector
Vector container
int array[5] = {12, 7, 9, 21, 13 };
Vector<int> v(array,array+5);
12 7 9 21 13
v.begin();
12 7 9 21
13
v.push_back(15);
12 7 9 21
…
15
12 7 9 21 15
v[3]
0 1 2 3 4
v.pop_back();
Some function of list class
• list functions for object t
– t.sort()
• Sorts in ascending order
– t.splice(iterator, otherObject );
• Inserts values from otherObject before iterator
– t.merge( otherObject )
• Removes otherObject and inserts it into t, sorted
– t.unique()
• Removes duplicate elements
Functions of list class cntd-
• list functions
– t.swap(otherObject);
• Exchange contents
– t.assign(iterator1, iterator2)
• Replaces contents with elements in range of iterators
– t.remove(value)
• Erases all instances of value
List container
int array[5] = {12, 7, 9, 21, 13 };
list<int> li(array,array+5);
7 9 21
12
li.push_front(8);
12 7 9 21
…
15
li.pop_front();
12 9 21
13
li.push_back(15);
12 7 9 21
…
15
li.pop_back();
8
7 12 17 21 23
li.insert()
19
Functions of dequeue class
• dequeue functions for object d
-d.front()
-Return a reference (or const_reference) to the first
component of d
-d.back()
-Return a reference (or const_reference) to the last
component of d.
-d.size()
-Return a value of type size_type giving the number of
values currently in d.
Functions of dequeue class contd-
-d.push_back(val)
-Add val to the end of d, increasing the size of d by one.
-d.push_front(val)
-Add val to the front of d, increasing the size of d by one.
-d.pop_back()
-Delete the last value of d. The size of d is reduced by
one.
-d.pop_front()
-Delete the first value of d. The size of d is reduced by
one.
Associative Containers
– Offer O(log n) insertion, suppression and access
– Store only weakly strict ordered types (eg. numeric
types)
• Must have operator<() and operator==() defined
and !(a<b) && !(b<a) (a==b)≡
– The sorting criterion is also a template parameter
– set<T> – the item stored act as key, no duplicates
– multiset<T> – set allowing duplicate items
– map<K,V> – separate key and value, no duplicates
– multimap<K,V> – map allowing duplicate keys
– hashed associative containers may be available
Container adaptors
• Container adapters
– stack, queue and priority_queue
– Not first class containers
• Do not support iterators
• Do not provide actual data structure
– Programmer can select implementation
– Member functions push and pop
Iterators
• Iterators are pointer-like entities that are used to
access individual elements in a container.
• Often they are used to move sequentially from
element to element, a process called iterating
through a container.
vector<int>
array_
17
4
23
12
size_ 4
vector<int>::iterator
Theiterator corresponding to
the class vector<int> is of
the typevector<int>::iterator
Iterators contd-
• The member functions begin() and end() return an
iterator to the first and past the last element of a
container
vector<int> v
array_ 17
4
23
12
size_ 4
v.end()
v.begin()
Iterators Categories
• Not every iterator can be used with every container for
example the list class provides no random access iterator
• Every algorithm requires an iterator with a certain level of
capability for example to use the [] operator you need a
random access iterator
• Iterators are divided into five categories in which a higher
(more specific) category always subsumes a lower (more
general) category, e.g. An algorithm that
accepts a forward iterator will also work with a bidirectional
iterator and a random access iterator
input
output
forward bidirectional
random
access
Algorithms
Algorithms in the STL are procedures
that are applied to containers to process
their data, for example search for an
element in an array, or sort an array.
For_Each() Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
void show(int n)
{
cout << n << ” ”;
}
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); // initialize vector with C array
for_each (v.begin(), v.end(), show); // apply function show
// to each element of vector v
Find() Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
int key;
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
cout << ”enter value :”;
cin >> key;
iter=find(v.begin(),v.end(),key); // finds integer key in v
if (iter != v.end()) // found the element
cout << ”Element ” << key << ” found” << endl;
else
cout << ”Element ” << key << ” not in vector v” << endl;
Sort & Merge
• Sort and merge allow you to sort and merge
elements in a container
#include <list>
int arr1[]= { 6, 4, 9, 1, 7 };
int arr2[]= { 4, 2, 1, 3, 8 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
l1.sort(); // l1 = {1, 4, 6, 7, 9}
l2.sort(); // l2= {1, 2, 3, 4, 8 }
l1.merge(l2); // merges l2 into l1
// l1 = { 1, 1, 2, 3, 4, 4, 6, 7, 8, 9}, l2= {}
Functions Objects
• Some algorithms like sort, merge, accumulate can take a
function object as argument.
• A function object is an object of a template class that has a
single member function : the overloaded operator ()
• It is also possible to use user-written functions in place of
pre-defined function objects
#include <list>
#include <functional>
int arr1[]= { 6, 4, 9, 1, 7 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
l1.sort(greater<int>()); // uses function object greater<int>
// for sorting in reverse order l1 = { 9, 7, 6, 4, 1 }
Function Objects
• The accumulate algorithm accumulates data over the
elements of the containing, for example computing the sum of
elements
#include <list>
#include <functional>
#include <numeric>
int arr1[]= { 6, 4, 9, 1, 7 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
int sum = accumulate(l1.begin(), l1.end() , 0, plus<int>());
int sum = accumulate(l1.begin(), l1.end(),0); // equivalent
int fac = accumulate(l1.begin(), l1.end() , 0, times<int>());
User Defined Function Objects
class squared _sum // user-defined function object
{
public:
int operator()(int n1, int n2) { return n1+n2*n2; }
};
int sq = accumulate(l1.begin(), l1.end() , 0,
squared_sum() );
// computes the sum of squares
THANK YOU.!!!
So long and thanks for all the attention 
?

Contenu connexe

Tendances (20)

Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
stack & queue
stack & queuestack & queue
stack & queue
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Strings
StringsStrings
Strings
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
List in Python
List in PythonList in Python
List in Python
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 

En vedette

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryIlio Catallo
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)Hemant Jain
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryKumar Gaurav
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)Sangharsh agarwal
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryDuda Dornelles
 
Extreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on SupercomputersExtreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on SupercomputersToyotaro Suzumura
 
iterators-must-go
iterators-must-goiterators-must-go
iterators-must-goHiroshi Ono
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructorDa Mystic Sadi
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++ppd1961
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 
The State of Twitter: STL 2011
The State of Twitter: STL 2011The State of Twitter: STL 2011
The State of Twitter: STL 2011Infuz
 

En vedette (20)

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Csrf final
Csrf finalCsrf final
Csrf final
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 
Savitch ch 18
Savitch ch 18Savitch ch 18
Savitch ch 18
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Extreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on SupercomputersExtreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on Supercomputers
 
iterators-must-go
iterators-must-goiterators-must-go
iterators-must-go
 
1.5.5 stl
1.5.5 stl1.5.5 stl
1.5.5 stl
 
Stl design overview
Stl design overviewStl design overview
Stl design overview
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Iterator
IteratorIterator
Iterator
 
The State of Twitter: STL 2011
The State of Twitter: STL 2011The State of Twitter: STL 2011
The State of Twitter: STL 2011
 

Similaire à standard template library(STL) in C++

Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1blessyboban92
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Kenji HASUNUMA
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Kenji HASUNUMA
 
Proposals for new function in Java SE 9 and beyond
Proposals for new function in Java SE 9 and beyondProposals for new function in Java SE 9 and beyond
Proposals for new function in Java SE 9 and beyondBarry Feigenbaum
 
Standard template library
Standard template libraryStandard template library
Standard template libraryJancypriya M
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...gjcross
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 

Similaire à standard template library(STL) in C++ (20)

Collections
CollectionsCollections
Collections
 
Collections
CollectionsCollections
Collections
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Queue
QueueQueue
Queue
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
R training2
R training2R training2
R training2
 
2 b queues
2 b queues2 b queues
2 b queues
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
 
Proposals for new function in Java SE 9 and beyond
Proposals for new function in Java SE 9 and beyondProposals for new function in Java SE 9 and beyond
Proposals for new function in Java SE 9 and beyond
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
collections
collectionscollections
collections
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 

Dernier

Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational PhilosophyShuvankar Madhu
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17Celine George
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxAditiChauhan701637
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 

Dernier (20)

Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational Philosophy
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17
 
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdfPersonal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptx
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 

standard template library(STL) in C++

  • 1. Standard Template Library Prepared By - Sreejith S - - Rahul Babu R -
  • 2. Contents  Introduction To STL  Containers  Iterators Algorithms  Function Objects
  • 3. Introduction To STL • STL is Standard Template Library – Powerful, template-based components • Containers: template data structures • Iterators: like pointers, access elements of containers • Algorithms: data manipulation, searching, sorting, etc. – Object- oriented programming: reuse, reuse, reuse – Only an introduction to STL, a huge class library
  • 4. STL components overview • Data storage, data access and algorithms are separated – Containers hold data – Iterators access data – Algorithms, function objects manipulate data – Allocators... allocate data (mostly, we ignore them) Container Container Algorithm Container
  • 5. Container • A container is a way that stored data is organized in memory, for example an array of elements. Container Sequential Associative Container Adapters
  • 6. Container ctd- • Sequence containers – vector – deque – list • Associative containers – set – multiset – map – multimap • Container adapters – stack – queue
  • 7. Sequential Container – vector<T> – dynamic array • Offers random access, back insertion • Should be your default choice, but choose wisely • Backward compatible with C : &v[0] points to the first element – deque<T> – double-ended queue (usually array of arrays) • Offers random access, back and front insertion • Slower than vectors, no C compatibility – list<T> – 'traditional' doubly linked list • Don't expect random access, you can insert anywhere though
  • 8. Some functions of vector class -size() -provides the number of elements -push_back() -appends an element to the end -pop_back() -Erases the last element -begin() -Provides reference to last element -end() -Provides reference to end of vector
  • 9. Vector container int array[5] = {12, 7, 9, 21, 13 }; Vector<int> v(array,array+5); 12 7 9 21 13 v.begin(); 12 7 9 21 13 v.push_back(15); 12 7 9 21 … 15 12 7 9 21 15 v[3] 0 1 2 3 4 v.pop_back();
  • 10. Some function of list class • list functions for object t – t.sort() • Sorts in ascending order – t.splice(iterator, otherObject ); • Inserts values from otherObject before iterator – t.merge( otherObject ) • Removes otherObject and inserts it into t, sorted – t.unique() • Removes duplicate elements
  • 11. Functions of list class cntd- • list functions – t.swap(otherObject); • Exchange contents – t.assign(iterator1, iterator2) • Replaces contents with elements in range of iterators – t.remove(value) • Erases all instances of value
  • 12. List container int array[5] = {12, 7, 9, 21, 13 }; list<int> li(array,array+5); 7 9 21 12 li.push_front(8); 12 7 9 21 … 15 li.pop_front(); 12 9 21 13 li.push_back(15); 12 7 9 21 … 15 li.pop_back(); 8 7 12 17 21 23 li.insert() 19
  • 13. Functions of dequeue class • dequeue functions for object d -d.front() -Return a reference (or const_reference) to the first component of d -d.back() -Return a reference (or const_reference) to the last component of d. -d.size() -Return a value of type size_type giving the number of values currently in d.
  • 14. Functions of dequeue class contd- -d.push_back(val) -Add val to the end of d, increasing the size of d by one. -d.push_front(val) -Add val to the front of d, increasing the size of d by one. -d.pop_back() -Delete the last value of d. The size of d is reduced by one. -d.pop_front() -Delete the first value of d. The size of d is reduced by one.
  • 15. Associative Containers – Offer O(log n) insertion, suppression and access – Store only weakly strict ordered types (eg. numeric types) • Must have operator<() and operator==() defined and !(a<b) && !(b<a) (a==b)≡ – The sorting criterion is also a template parameter – set<T> – the item stored act as key, no duplicates – multiset<T> – set allowing duplicate items – map<K,V> – separate key and value, no duplicates – multimap<K,V> – map allowing duplicate keys – hashed associative containers may be available
  • 16. Container adaptors • Container adapters – stack, queue and priority_queue – Not first class containers • Do not support iterators • Do not provide actual data structure – Programmer can select implementation – Member functions push and pop
  • 17. Iterators • Iterators are pointer-like entities that are used to access individual elements in a container. • Often they are used to move sequentially from element to element, a process called iterating through a container. vector<int> array_ 17 4 23 12 size_ 4 vector<int>::iterator Theiterator corresponding to the class vector<int> is of the typevector<int>::iterator
  • 18. Iterators contd- • The member functions begin() and end() return an iterator to the first and past the last element of a container vector<int> v array_ 17 4 23 12 size_ 4 v.end() v.begin()
  • 19. Iterators Categories • Not every iterator can be used with every container for example the list class provides no random access iterator • Every algorithm requires an iterator with a certain level of capability for example to use the [] operator you need a random access iterator • Iterators are divided into five categories in which a higher (more specific) category always subsumes a lower (more general) category, e.g. An algorithm that accepts a forward iterator will also work with a bidirectional iterator and a random access iterator input output forward bidirectional random access
  • 20. Algorithms Algorithms in the STL are procedures that are applied to containers to process their data, for example search for an element in an array, or sort an array.
  • 21. For_Each() Algorithm #include <vector> #include <algorithm> #include <iostream> void show(int n) { cout << n << ” ”; } int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array for_each (v.begin(), v.end(), show); // apply function show // to each element of vector v
  • 22. Find() Algorithm #include <vector> #include <algorithm> #include <iostream> int key; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array vector<int>::iterator iter; cout << ”enter value :”; cin >> key; iter=find(v.begin(),v.end(),key); // finds integer key in v if (iter != v.end()) // found the element cout << ”Element ” << key << ” found” << endl; else cout << ”Element ” << key << ” not in vector v” << endl;
  • 23. Sort & Merge • Sort and merge allow you to sort and merge elements in a container #include <list> int arr1[]= { 6, 4, 9, 1, 7 }; int arr2[]= { 4, 2, 1, 3, 8 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 l1.sort(); // l1 = {1, 4, 6, 7, 9} l2.sort(); // l2= {1, 2, 3, 4, 8 } l1.merge(l2); // merges l2 into l1 // l1 = { 1, 1, 2, 3, 4, 4, 6, 7, 8, 9}, l2= {}
  • 24. Functions Objects • Some algorithms like sort, merge, accumulate can take a function object as argument. • A function object is an object of a template class that has a single member function : the overloaded operator () • It is also possible to use user-written functions in place of pre-defined function objects #include <list> #include <functional> int arr1[]= { 6, 4, 9, 1, 7 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 l1.sort(greater<int>()); // uses function object greater<int> // for sorting in reverse order l1 = { 9, 7, 6, 4, 1 }
  • 25. Function Objects • The accumulate algorithm accumulates data over the elements of the containing, for example computing the sum of elements #include <list> #include <functional> #include <numeric> int arr1[]= { 6, 4, 9, 1, 7 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 int sum = accumulate(l1.begin(), l1.end() , 0, plus<int>()); int sum = accumulate(l1.begin(), l1.end(),0); // equivalent int fac = accumulate(l1.begin(), l1.end() , 0, times<int>());
  • 26. User Defined Function Objects class squared _sum // user-defined function object { public: int operator()(int n1, int n2) { return n1+n2*n2; } }; int sq = accumulate(l1.begin(), l1.end() , 0, squared_sum() ); // computes the sum of squares
  • 27. THANK YOU.!!! So long and thanks for all the attention 
  • 28. ?