standard template library(STL) in C++

•sreejith •sree
•sreejith •sreeKenan and Interconnect billing developer um Tata Consultancy Services
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 
?
1 von 28

Recomendados

STL in C++ von
STL in C++STL in C++
STL in C++Surya Prakash Sahu
5.3K views77 Folien
Standard Template Library von
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
252 views36 Folien
Function overloading ppt von
Function overloading pptFunction overloading ppt
Function overloading pptProf. Dr. K. Adisesha
783 views17 Folien
07. Virtual Functions von
07. Virtual Functions07. Virtual Functions
07. Virtual FunctionsHaresh Jaiswal
18.4K views20 Folien
classes and objects in C++ von
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
14K views51 Folien
Stl Containers von
Stl ContainersStl Containers
Stl Containersppd1961
2K views41 Folien

Más contenido relacionado

Was ist angesagt?

Standard template library von
Standard template libraryStandard template library
Standard template librarySukriti Singh
1.7K views33 Folien
Templates in C++ von
Templates in C++Templates in C++
Templates in C++Tech_MX
18.1K views21 Folien
Data types in c++ von
Data types in c++Data types in c++
Data types in c++Venkata.Manish Reddy
10.1K views23 Folien
Pure virtual function and abstract class von
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
457 views17 Folien
Pointer in c von
Pointer in cPointer in c
Pointer in clavanya marichamy
15.5K views14 Folien
Constructor and Types of Constructors von
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
2.8K views14 Folien

Was ist angesagt?(20)

Standard template library von Sukriti Singh
Standard template libraryStandard template library
Standard template library
Sukriti Singh1.7K views
Templates in C++ von Tech_MX
Templates in C++Templates in C++
Templates in C++
Tech_MX18.1K views
Pure virtual function and abstract class von Amit Trivedi
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
Amit Trivedi457 views
Constructor and Types of Constructors von Dhrumil Panchal
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal2.8K views
linked list in data structure von shameen khan
linked list in data structure linked list in data structure
linked list in data structure
shameen khan39.2K views
Arrays in python von moazamali28
Arrays in pythonArrays in python
Arrays in python
moazamali283.3K views
sparse matrix in data structure von MAHALAKSHMI P
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P2.5K views
Operator Overloading von Nilesh Dalvi
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi27.4K views

Destacado

C++ Standard Template Library von
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryIlio Catallo
2.5K views202 Folien
Stl (standard template library) von
Stl (standard template library)Stl (standard template library)
Stl (standard template library)Hemant Jain
1.7K views19 Folien
Standard Template Library von
Standard Template LibraryStandard Template Library
Standard Template LibraryKumar Gaurav
1.9K views29 Folien
How to choose best containers in STL (C++) von
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
13.3K views29 Folien
Lecture11 standard template-library von
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
2.5K views22 Folien
Stl algorithm-Basic types von
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic typesmohamed sikander
387 views16 Folien

Destacado(20)

C++ Standard Template Library von Ilio Catallo
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
Ilio Catallo2.5K views
Stl (standard template library) von Hemant Jain
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
Hemant Jain1.7K views
Standard Template Library von Kumar Gaurav
Standard Template LibraryStandard Template Library
Standard Template Library
Kumar Gaurav1.9K views
How to choose best containers in STL (C++) von Sangharsh agarwal
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 agarwal13.3K views
Lecture11 standard template-library von Hariz Mustafa
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
Hariz Mustafa2.5K views
Extreme Scale Breadth-First Search on Supercomputers von Toyotaro Suzumura
Extreme Scale Breadth-First Search on SupercomputersExtreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on Supercomputers
Toyotaro Suzumura509 views
Generalized Functors - Realizing Command Design Pattern in C++ von ppd1961
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
ppd19616.2K views
Iterator - a powerful but underappreciated design pattern von Nitin Bhide
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
Nitin Bhide4K views
The State of Twitter: STL 2011 von Infuz
The State of Twitter: STL 2011The State of Twitter: STL 2011
The State of Twitter: STL 2011
Infuz6.1K views

Similar a standard template library(STL) in C++

Collections von
CollectionsCollections
CollectionsManav Prasad
267 views24 Folien
Collections von
CollectionsCollections
CollectionsRajkattamuri
231 views23 Folien
Collections in Java von
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
815 views23 Folien
JavaScript.pptx von
JavaScript.pptxJavaScript.pptx
JavaScript.pptxpramod599939
3 views13 Folien
Queue von
QueueQueue
QueueAyaz Akhtar
179 views25 Folien
Scala collections api expressivity and brevity upgrade from java von
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
677 views9 Folien

Similar a standard template library(STL) in C++(20)

Collections in Java von Khasim Cise
Collections in JavaCollections in Java
Collections in Java
Khasim Cise815 views
Scala collections api expressivity and brevity upgrade from java von IndicThreads
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
IndicThreads677 views
02._Object-Oriented_Programming_Concepts.ppt von Yonas D. Ebren
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren2 views
Programming with Python - Week 3 von Ahmet Bulut
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut648 views
Collections Framework Beginners Guide 2 von Kenji HASUNUMA
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
Kenji HASUNUMA69 views
Collections Framework Begineers guide 2 von Kenji HASUNUMA
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA27 views
Proposals for new function in Java SE 9 and beyond von Barry Feigenbaum
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
Barry Feigenbaum945 views
Standard template library von Jancypriya M
Standard template libraryStandard template library
Standard template library
Jancypriya M228 views
Processing data with Python, using standard library modules you (probably) ne... von gjcross
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...
gjcross1.8K views
Taxonomy of Scala von shinolajla
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla10.1K views
16. Arrays Lists Stacks Queues von Intro C# Book
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book30.2K views

Último

CUNY IT Picciano.pptx von
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptxapicciano
60 views17 Folien
Create a Structure in VBNet.pptx von
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptxBreach_P
82 views8 Folien
Six Sigma Concept by Sahil Srivastava.pptx von
Six Sigma Concept by Sahil Srivastava.pptxSix Sigma Concept by Sahil Srivastava.pptx
Six Sigma Concept by Sahil Srivastava.pptxSahil Srivastava
40 views11 Folien
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... von
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...Nguyen Thanh Tu Collection
71 views91 Folien
Mineral nutrition and Fertilizer use of Cashew von
 Mineral nutrition and Fertilizer use of Cashew Mineral nutrition and Fertilizer use of Cashew
Mineral nutrition and Fertilizer use of CashewAruna Srikantha Jayawardana
53 views107 Folien
JQUERY.pdf von
JQUERY.pdfJQUERY.pdf
JQUERY.pdfArthyR3
103 views22 Folien

Último(20)

CUNY IT Picciano.pptx von apicciano
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptx
apicciano60 views
Create a Structure in VBNet.pptx von Breach_P
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptx
Breach_P82 views
Six Sigma Concept by Sahil Srivastava.pptx von Sahil Srivastava
Six Sigma Concept by Sahil Srivastava.pptxSix Sigma Concept by Sahil Srivastava.pptx
Six Sigma Concept by Sahil Srivastava.pptx
Sahil Srivastava40 views
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... von Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
JQUERY.pdf von ArthyR3
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
ArthyR3103 views
12.5.23 Poverty and Precarity.pptx von mary850239
12.5.23 Poverty and Precarity.pptx12.5.23 Poverty and Precarity.pptx
12.5.23 Poverty and Precarity.pptx
mary850239162 views
Parts of Speech (1).pptx von mhkpreet001
Parts of Speech (1).pptxParts of Speech (1).pptx
Parts of Speech (1).pptx
mhkpreet00143 views
The Accursed House by Émile Gaboriau von DivyaSheta
The Accursed House  by Émile GaboriauThe Accursed House  by Émile Gaboriau
The Accursed House by Émile Gaboriau
DivyaSheta246 views
EILO EXCURSION PROGRAMME 2023 von info33492
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023
info33492181 views
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx von Niranjan Chavan
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptxSURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx
Niranjan Chavan43 views

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. ?