SlideShare une entreprise Scribd logo
1  sur  22
Lecture 11




  Standard Template Library
            (STL)




TCP1201 OOPDS                 1
Learning Objectives
 To understand the components of
  Standard Template Library (STL).
 To understand how and when to use
  STL’s vector, set, multiset, map, and
  multimap.
 To understand how to use iterator.
 To understand how to use STL find and
  sort algorithms.




    TCP1201 OOPDS                         2
Standard Template Library (STL)
STL provides powerful, template-based, reusable
components that implement many common data
structures and algorithms used to process those data
structures.
The STL was conceived and designed for
performance and flexibility.




   TCP1201 OOPDS                                   3
STL Components
STL has 3 components (CIA):
Containers, Algorithms, Iterators.
Containers: Containers are data structures or a
collection of objects. Example:
vector, list, set, map, etc.
Iterators: Iterators are similar to pointers and are used
to point to container elements.
Algorithms: Algorithm are functions for processing
container elements. Example: copy, sort, find, etc.




   TCP1201 OOPDS                                       4
STL Containers
STL has many containers, divided into 3 groups:
sequential, associative, adaptor.
Sequential containers represent linear data structures,
e.g. vectors, list, deque.
Associative containers are nonlinear containers that
typically can locate (search) elements stored in the
containers quickly, e.g. set, multiset, map,
multimap.
Container adapters are simply variations of the above
containers, e.g. stack, queue, priority_queue. The
container adapters do not support iterators.



   TCP1201 OOPDS                                       5
Useful Sequential Containers
 Container                         Description
list         Bidirectional/Doubly linked list.
             Best for rapid insertion and deletion anywhere.
vector       "Array" that grows automatically,
             Best for rapid insertion and deletion at back.
             Support direct access to any elementvia operator "[]".
deque        "Array" that grows automatically.
             Best for rapid insertion and deletion at front and back.




   TCP1201 OOPDS                                                        6
Useful Associative Containers
 Container                         Description
set          No duplicate element allowed.
             Elements are automatically sorted.
             Best for rapid lookup (searching) of element.
multiset     set that allows duplicate elements.
map          Collection of (key, value) pairs with non-duplicate key.
             Elements are automatically sorted by key.
             Best for rapid lookup of key.
multimap     map that allows duplicate keys.




      TCP1201 OOPDS                                                     7
Useful Container Adaptors
   Container                            Description
stack            Last-in, first-out (LIFO) data structure.
queue            First-in, first-out (FIFO) data structure.
priority_queue   Highest priority element is always the first element
                 out.




   TCP1201 OOPDS                                                    8
STL Iterator
Iterators are similar to pointers and are used to point to
container elements.
The dereferencing operator (*) dereferences an iterator
so that you can use the element to which it points.
The ++ operation on an iterator moves it to the
container’s next element.
Container's begin method returns an iterator pointing to
the first element of the container.
Container's end method returns an iterator pointing to
the first element past the end of the container (an
element that doesn’t exist).


   TCP1201 OOPDS                                       9
Iterator Example
#include <iostream>                              Output:
#include <vector>                                4 2 7 6
using namespace std;
                                                 4 2 7 6
int main() {
  vector<int> v;
  v.push_back(4);                                Iterator type must
  v.push_back(2);
  v.push_back(7);                                match container type.
  v.push_back(6);

    for (int i = 0; i < v.size(); i++)           Initialize iterator it to
      cout << v[i] << " ";
    cout << endl;                                the first element of
                                                 container.
    // Same result as 'for' loop.
    for (vector<int>::iterator it = v.begin();
         it != v.end();
         it++)                                   Move to the next
      cout << *it << " ";                        element.
    cout << endl;
}
                                                 Use iterator it like a
                                                 pointer.

       TCP1201 OOPDS                                               10
STL Algorithms
Many STL algorithms accept iterator as function
argument. See next slide for sort function.
Many STL algorithms returns an iterator. See the
example on STL set class for find function.




   TCP1201 OOPDS                                   11
STL Algorithm sort
#include <iostream>
#include <algorithm> // sort()
#include <vector>
using namespace std;
int main() {
  vector<int> v;
  v.push_back(4);
  v.push_back(2);
  v.push_back(7);                             vector elements can
  v.push_back(6);                             be sorted using STL
  cout << "Vector elements unsorted:n";      algorithm sort
  for (int i = 0; i < v.size(); i++)
     cout << v[i] << " ";
                                              function

    sort (v.begin(), v.end());
    cout << "nVector elements sorted:n";   Vector elements unsorted:
    for (int i = 0; i < v.size(); i++)       4 2 7 6
       cout << v[i] << " ";                  Vector elements sorted:
}                                            2 4 6 7




      TCP1201 OOPDS                                           12
STL set Class
A set is a collection of non-duplicate sorted elements called keys.
                        set <key_type> s;
key_type is the data types of the key/element.

Use set when you want a sorted collection and you do not need
random access to its elements.
Use insert() method to insert an element into a set:
                        set <int> s;
                        s.insert (321);

Duplicates are ignored when inserted.
iterator is required to iterate/visit the elements in set. Operator[] is
not supported.
Use find() method to look up a specified key in a set .

      TCP1201 OOPDS                                              13
STL set Class
#include <iostream>                          Output1:
#include <set>                               -999
using namespace std;                         18
int main() {                                 321
  set<int> s;                                Enter an integer:
  s.insert (321);                            5
  s.insert (-999);                           5 is not in set.
  s.insert (18);
  s.insert (-999); // duplicate is ignored
  set<int>::iterator it = s.begin();
  while (it != s.end())                      Use iterator to
    cout << *it++ << endl; // -999 18 321    iterate the set.
  int target;
  cout << "Enter an integer: ";              Output2:
  cin >> target;                             -999
  it = s.find (target);                      18
  if (it == s.end()) // not found            321
    cout << target << " is NOT in set.";     Enter an integer:
  else                                       321
    cout << target << " is IN set.";         321 is IN set.
}


    TCP1201 OOPDS                                          14
STL multiset Class
#include <iostream>                    Output:
#include <set>                         -999
using namespace std;                   -999
int main() {                           18
  multiset<int> s;                     321
  s.insert (321);
  s.insert (-999);
  s.insert (18);
  s.insert (-999); // duplicate
  set<int>::iterator it = s.begin();
  while (it != s.end())                multiset allows
    cout << *it++ << endl;             duplicate keys
}




    TCP1201 OOPDS                                  15
STL map Class
A map is a collection of (key,value) pairs sorted by the keys.

           map <key_type, value_type> m;
key_type and value_type are the data types of the key and
the value respectively.

In array the index is always int starting from 0, whereas in
map the key can be of other data type.

map cannot contain duplicate key (multimap can).

     map <char, string> m;
     m['A'] = "Apple";
     m['A'] = "Angel"; // key 'A' already in the
                       // map, new 'A' is ignored.
                       // m['A'] is still "Apple".

  TCP1201 OOPDS                                                16
STL map Class
#include <iostream>                       char key;
#include <string>                         cout << "Enter a char: ";
#include <map> // map, multimap           cin >> key;
using namespace std;                      it = m.find (key);
int main() {                              if (it == m.end())
  map <char, string> m;                     cout << key
  m['C'] = "Cat";   // insert                    << " is NOT in map.";
  m['A'] = "Apple";                       else
  m['B'] = "Boy";                           cout << key << " is IN map.";
  cout << m['A'] << " " // retrieve   }
       << m['B'] << " "
       << m['C'] << endl;

 map <char, string>::iterator it;
 it = m.begin();                              first refers to the key of
 while (it != m.end()) {
   cout << it->first << " "                   current element whereas
         << it->second << endl;               second refers to the value
   it++;                                      of of current element
 }



      TCP1201 OOPDS                                              17
STL map Class
#include <iostream>                       char key;
#include <string>                         cout << "Enter a char: ";
#include <map> // map, multimap           cin >> key;
using namespace std;                      it = m.find (key);
int main() {                              if (it == m.end())
  map <char, string> m;                     cout << key
  m['C'] = "Cat";   // insert                    << " is NOT in map.";
  m['A'] = "Apple";                       else
  m['B'] = "Boy";                           cout << key << " is IN map.";
  cout << m['A'] << " " // retrieve   }
       << m['B'] << " "
       << m['C'] << endl;
                                      Output 1:          Output 2:
 map <char, string>::iterator it;     Apple Boy Cat      Apple Boy Cat
 it = m.begin();                      A Apple            A Apple
 while (it != m.end()) {              B Boy              B Boy
   cout << it->first << " "           C Cat              C Cat
         << it->second << endl;       Enter a char: Z    Enter a char: C
   it++;                              Z is NOT in map    C is IN map
 }



      TCP1201 OOPDS                                              18
STL multimap Class
A multimap is similar to map but it allows duplicate keys.

However, insert method and a pair object must be used
when inserting a (key,value) pair into multimap.

The pair object and the multimap must have the same key
type and value type.

Operator [ ] is not supported. Iterator must be used to locate a
element.

  multimap <char,string> mm;
  mm.insert (pair<char,string>('A',"Apple"));
  mm.insert (pair<char,string>('A',"Angel"));
  // mm has 2 elements with 'A' as key.




  TCP1201 OOPDS                                               19
STL multimap Class
#include <iostream>                       char key;
#include <string>                         cout << "Enter a char: ";
#include <map> // map, multimap           cin >> key;
using namespace std;                      it = mm.find (key);
int main() {                              if (it == mm.end())
  multimap <char,string> mm;                cout << key
  mm.insert (                                    << " is NOT in map.";
   pair<char,string>('C',"Cat"));         else
  mm.insert (                               cout << key << " is IN map.";
   pair<char,string>('A',"Apple"));   }
  mm.insert (
   pair<char,string>('B',"Boy"));
  mm.insert (                         Output 1:          Output 2:
   pair<char,string>('A',"Angle"));   A Apple            A Apple
                                      A Angle            A Angle
 map <char, string>::iterator it;     B Boy              B Boy
 it = mm.begin();                     C Cat              C Cat
 while (it != mm.end()) {             Enter a char: Z    Enter a char: C
   cout << it->first << " "           Z is NOT in map    C is IN map
         << it->second << endl;
   it++;
 }
      TCP1201 OOPDS                                              20
STL less and greater Function Objects
By default, STL sort function, set, map, and other
classes use the STL less function object to sort the
elements from the smallest element first to the largest.
To sort by the largest element first, pass the STL
greater function object to the STL container
constructor.

   set <int> s1;                // Smallest to largest.
   set <int, less<int> > s2;    // Same sorting as s1.
   set <int, greater<int> > s3; // Largest to smallest.




   TCP1201 OOPDS                                      21
STL greater Function Object
#include <iostream>                    Output:
#include <set>                         321
using namespace std;                   18
int main() {                           -999
  multiset<int, greater<int> > s;      -999
  s.insert (321);
  s.insert (-999);
  s.insert (18);
  s.insert (-999); // duplicate
  set<int>::iterator it = s.begin();
  while (it != s.end())                Largest first
    cout << *it++ << endl;
}




    TCP1201 OOPDS                                      22

Contenu connexe

Tendances

standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 
Stl Containers
Stl ContainersStl Containers
Stl Containersppd1961
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)Hemant Jain
 
Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2Hariz Mustafa
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++Jawad Khan
 

Tendances (20)

standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
 
STL in C++
STL in C++STL in C++
STL in C++
 
Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Arrays
ArraysArrays
Arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 

Similaire à Lecture11 standard template-library

Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematicakrasul
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within MathematicaShoaib Burq
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingMeghaj Mallick
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++NUST Stuff
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfaathiauto
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 

Similaire à Lecture11 standard template-library (20)

C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematica
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within Mathematica
 
STLStack.pdf
STLStack.pdfSTLStack.pdf
STLStack.pdf
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
The STL
The STLThe STL
The STL
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Arrays
ArraysArrays
Arrays
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 

Plus de Hariz Mustafa

Lecture04 polymorphism
Lecture04 polymorphismLecture04 polymorphism
Lecture04 polymorphismHariz Mustafa
 
Lecture03 inheritance
Lecture03 inheritanceLecture03 inheritance
Lecture03 inheritanceHariz Mustafa
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programmingHariz Mustafa
 
Topic6decisionmaking
Topic6decisionmakingTopic6decisionmaking
Topic6decisionmakingHariz Mustafa
 
Topic5cognition and problem_solving
Topic5cognition and problem_solvingTopic5cognition and problem_solving
Topic5cognition and problem_solvingHariz Mustafa
 
Problem solving activities
Problem solving activitiesProblem solving activities
Problem solving activitiesHariz Mustafa
 
Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3Hariz Mustafa
 
Decision making scenarios
Decision making scenariosDecision making scenarios
Decision making scenariosHariz Mustafa
 
Cognition and problem_solving
Cognition and problem_solvingCognition and problem_solving
Cognition and problem_solvingHariz Mustafa
 
Chapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_iiChapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_iiHariz Mustafa
 
Ch08 evaluating arguments
Ch08 evaluating argumentsCh08 evaluating arguments
Ch08 evaluating argumentsHariz Mustafa
 
Chapter 5 logical_fallacies_i
Chapter 5 logical_fallacies_iChapter 5 logical_fallacies_i
Chapter 5 logical_fallacies_iHariz Mustafa
 
Ch03 basic logical_concepts
Ch03 basic logical_conceptsCh03 basic logical_concepts
Ch03 basic logical_conceptsHariz Mustafa
 

Plus de Hariz Mustafa (20)

Lecture10 trees v3
Lecture10 trees v3Lecture10 trees v3
Lecture10 trees v3
 
Lecture09 recursion
Lecture09 recursionLecture09 recursion
Lecture09 recursion
 
Lecture04 polymorphism
Lecture04 polymorphismLecture04 polymorphism
Lecture04 polymorphism
 
Lecture03 inheritance
Lecture03 inheritanceLecture03 inheritance
Lecture03 inheritance
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
Topic6decisionmaking
Topic6decisionmakingTopic6decisionmaking
Topic6decisionmaking
 
Topic5cognition and problem_solving
Topic5cognition and problem_solvingTopic5cognition and problem_solving
Topic5cognition and problem_solving
 
Topic2 argument
Topic2 argumentTopic2 argument
Topic2 argument
 
Topic2
Topic2Topic2
Topic2
 
Topic 1
Topic 1Topic 1
Topic 1
 
Problem solving activities
Problem solving activitiesProblem solving activities
Problem solving activities
 
Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3
 
Decision making scenarios
Decision making scenariosDecision making scenarios
Decision making scenarios
 
Decision making
Decision makingDecision making
Decision making
 
Cognition and problem_solving
Cognition and problem_solvingCognition and problem_solving
Cognition and problem_solving
 
Chapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_iiChapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_ii
 
Chapter 4 language
Chapter 4 languageChapter 4 language
Chapter 4 language
 
Ch08 evaluating arguments
Ch08 evaluating argumentsCh08 evaluating arguments
Ch08 evaluating arguments
 
Chapter 5 logical_fallacies_i
Chapter 5 logical_fallacies_iChapter 5 logical_fallacies_i
Chapter 5 logical_fallacies_i
 
Ch03 basic logical_concepts
Ch03 basic logical_conceptsCh03 basic logical_concepts
Ch03 basic logical_concepts
 

Lecture11 standard template-library

  • 1. Lecture 11 Standard Template Library (STL) TCP1201 OOPDS 1
  • 2. Learning Objectives  To understand the components of Standard Template Library (STL).  To understand how and when to use STL’s vector, set, multiset, map, and multimap.  To understand how to use iterator.  To understand how to use STL find and sort algorithms. TCP1201 OOPDS 2
  • 3. Standard Template Library (STL) STL provides powerful, template-based, reusable components that implement many common data structures and algorithms used to process those data structures. The STL was conceived and designed for performance and flexibility. TCP1201 OOPDS 3
  • 4. STL Components STL has 3 components (CIA): Containers, Algorithms, Iterators. Containers: Containers are data structures or a collection of objects. Example: vector, list, set, map, etc. Iterators: Iterators are similar to pointers and are used to point to container elements. Algorithms: Algorithm are functions for processing container elements. Example: copy, sort, find, etc. TCP1201 OOPDS 4
  • 5. STL Containers STL has many containers, divided into 3 groups: sequential, associative, adaptor. Sequential containers represent linear data structures, e.g. vectors, list, deque. Associative containers are nonlinear containers that typically can locate (search) elements stored in the containers quickly, e.g. set, multiset, map, multimap. Container adapters are simply variations of the above containers, e.g. stack, queue, priority_queue. The container adapters do not support iterators. TCP1201 OOPDS 5
  • 6. Useful Sequential Containers Container Description list Bidirectional/Doubly linked list. Best for rapid insertion and deletion anywhere. vector "Array" that grows automatically, Best for rapid insertion and deletion at back. Support direct access to any elementvia operator "[]". deque "Array" that grows automatically. Best for rapid insertion and deletion at front and back. TCP1201 OOPDS 6
  • 7. Useful Associative Containers Container Description set No duplicate element allowed. Elements are automatically sorted. Best for rapid lookup (searching) of element. multiset set that allows duplicate elements. map Collection of (key, value) pairs with non-duplicate key. Elements are automatically sorted by key. Best for rapid lookup of key. multimap map that allows duplicate keys. TCP1201 OOPDS 7
  • 8. Useful Container Adaptors Container Description stack Last-in, first-out (LIFO) data structure. queue First-in, first-out (FIFO) data structure. priority_queue Highest priority element is always the first element out. TCP1201 OOPDS 8
  • 9. STL Iterator Iterators are similar to pointers and are used to point to container elements. The dereferencing operator (*) dereferences an iterator so that you can use the element to which it points. The ++ operation on an iterator moves it to the container’s next element. Container's begin method returns an iterator pointing to the first element of the container. Container's end method returns an iterator pointing to the first element past the end of the container (an element that doesn’t exist). TCP1201 OOPDS 9
  • 10. Iterator Example #include <iostream> Output: #include <vector> 4 2 7 6 using namespace std; 4 2 7 6 int main() { vector<int> v; v.push_back(4); Iterator type must v.push_back(2); v.push_back(7); match container type. v.push_back(6); for (int i = 0; i < v.size(); i++) Initialize iterator it to cout << v[i] << " "; cout << endl; the first element of container. // Same result as 'for' loop. for (vector<int>::iterator it = v.begin(); it != v.end(); it++) Move to the next cout << *it << " "; element. cout << endl; } Use iterator it like a pointer. TCP1201 OOPDS 10
  • 11. STL Algorithms Many STL algorithms accept iterator as function argument. See next slide for sort function. Many STL algorithms returns an iterator. See the example on STL set class for find function. TCP1201 OOPDS 11
  • 12. STL Algorithm sort #include <iostream> #include <algorithm> // sort() #include <vector> using namespace std; int main() { vector<int> v; v.push_back(4); v.push_back(2); v.push_back(7); vector elements can v.push_back(6); be sorted using STL cout << "Vector elements unsorted:n"; algorithm sort for (int i = 0; i < v.size(); i++) cout << v[i] << " "; function sort (v.begin(), v.end()); cout << "nVector elements sorted:n"; Vector elements unsorted: for (int i = 0; i < v.size(); i++) 4 2 7 6 cout << v[i] << " "; Vector elements sorted: } 2 4 6 7 TCP1201 OOPDS 12
  • 13. STL set Class A set is a collection of non-duplicate sorted elements called keys. set <key_type> s; key_type is the data types of the key/element. Use set when you want a sorted collection and you do not need random access to its elements. Use insert() method to insert an element into a set: set <int> s; s.insert (321); Duplicates are ignored when inserted. iterator is required to iterate/visit the elements in set. Operator[] is not supported. Use find() method to look up a specified key in a set . TCP1201 OOPDS 13
  • 14. STL set Class #include <iostream> Output1: #include <set> -999 using namespace std; 18 int main() { 321 set<int> s; Enter an integer: s.insert (321); 5 s.insert (-999); 5 is not in set. s.insert (18); s.insert (-999); // duplicate is ignored set<int>::iterator it = s.begin(); while (it != s.end()) Use iterator to cout << *it++ << endl; // -999 18 321 iterate the set. int target; cout << "Enter an integer: "; Output2: cin >> target; -999 it = s.find (target); 18 if (it == s.end()) // not found 321 cout << target << " is NOT in set."; Enter an integer: else 321 cout << target << " is IN set."; 321 is IN set. } TCP1201 OOPDS 14
  • 15. STL multiset Class #include <iostream> Output: #include <set> -999 using namespace std; -999 int main() { 18 multiset<int> s; 321 s.insert (321); s.insert (-999); s.insert (18); s.insert (-999); // duplicate set<int>::iterator it = s.begin(); while (it != s.end()) multiset allows cout << *it++ << endl; duplicate keys } TCP1201 OOPDS 15
  • 16. STL map Class A map is a collection of (key,value) pairs sorted by the keys. map <key_type, value_type> m; key_type and value_type are the data types of the key and the value respectively. In array the index is always int starting from 0, whereas in map the key can be of other data type. map cannot contain duplicate key (multimap can). map <char, string> m; m['A'] = "Apple"; m['A'] = "Angel"; // key 'A' already in the // map, new 'A' is ignored. // m['A'] is still "Apple". TCP1201 OOPDS 16
  • 17. STL map Class #include <iostream> char key; #include <string> cout << "Enter a char: "; #include <map> // map, multimap cin >> key; using namespace std; it = m.find (key); int main() { if (it == m.end()) map <char, string> m; cout << key m['C'] = "Cat"; // insert << " is NOT in map."; m['A'] = "Apple"; else m['B'] = "Boy"; cout << key << " is IN map."; cout << m['A'] << " " // retrieve } << m['B'] << " " << m['C'] << endl; map <char, string>::iterator it; it = m.begin(); first refers to the key of while (it != m.end()) { cout << it->first << " " current element whereas << it->second << endl; second refers to the value it++; of of current element } TCP1201 OOPDS 17
  • 18. STL map Class #include <iostream> char key; #include <string> cout << "Enter a char: "; #include <map> // map, multimap cin >> key; using namespace std; it = m.find (key); int main() { if (it == m.end()) map <char, string> m; cout << key m['C'] = "Cat"; // insert << " is NOT in map."; m['A'] = "Apple"; else m['B'] = "Boy"; cout << key << " is IN map."; cout << m['A'] << " " // retrieve } << m['B'] << " " << m['C'] << endl; Output 1: Output 2: map <char, string>::iterator it; Apple Boy Cat Apple Boy Cat it = m.begin(); A Apple A Apple while (it != m.end()) { B Boy B Boy cout << it->first << " " C Cat C Cat << it->second << endl; Enter a char: Z Enter a char: C it++; Z is NOT in map C is IN map } TCP1201 OOPDS 18
  • 19. STL multimap Class A multimap is similar to map but it allows duplicate keys. However, insert method and a pair object must be used when inserting a (key,value) pair into multimap. The pair object and the multimap must have the same key type and value type. Operator [ ] is not supported. Iterator must be used to locate a element. multimap <char,string> mm; mm.insert (pair<char,string>('A',"Apple")); mm.insert (pair<char,string>('A',"Angel")); // mm has 2 elements with 'A' as key. TCP1201 OOPDS 19
  • 20. STL multimap Class #include <iostream> char key; #include <string> cout << "Enter a char: "; #include <map> // map, multimap cin >> key; using namespace std; it = mm.find (key); int main() { if (it == mm.end()) multimap <char,string> mm; cout << key mm.insert ( << " is NOT in map."; pair<char,string>('C',"Cat")); else mm.insert ( cout << key << " is IN map."; pair<char,string>('A',"Apple")); } mm.insert ( pair<char,string>('B',"Boy")); mm.insert ( Output 1: Output 2: pair<char,string>('A',"Angle")); A Apple A Apple A Angle A Angle map <char, string>::iterator it; B Boy B Boy it = mm.begin(); C Cat C Cat while (it != mm.end()) { Enter a char: Z Enter a char: C cout << it->first << " " Z is NOT in map C is IN map << it->second << endl; it++; } TCP1201 OOPDS 20
  • 21. STL less and greater Function Objects By default, STL sort function, set, map, and other classes use the STL less function object to sort the elements from the smallest element first to the largest. To sort by the largest element first, pass the STL greater function object to the STL container constructor. set <int> s1; // Smallest to largest. set <int, less<int> > s2; // Same sorting as s1. set <int, greater<int> > s3; // Largest to smallest. TCP1201 OOPDS 21
  • 22. STL greater Function Object #include <iostream> Output: #include <set> 321 using namespace std; 18 int main() { -999 multiset<int, greater<int> > s; -999 s.insert (321); s.insert (-999); s.insert (18); s.insert (-999); // duplicate set<int>::iterator it = s.begin(); while (it != s.end()) Largest first cout << *it++ << endl; } TCP1201 OOPDS 22