SlideShare une entreprise Scribd logo
1  sur  23
STANDARD TEMPLATE
LIBRARIES
Michael Heron
Introduction
• The great promise of object orientation is reusability.
• As of now, we haven’t done much re-using.
• In the same way that Java provides comprehensive
libraries of basic structures, so too does C++
• Through the mechanism of the Standard Template Library.
Standard Template Library
• The STL is not a part of the core C++ language.
• It’s a set of extended libraries that have nearly
ubiquitous applicability.
• They are defined in the C++ standard.
• It provides implementations of many of the
standard data types available in other languages.
• It is driven by the power of templates (as
discussed in the previous lecture).
Standard Template Library
• The STL subset that we are going to pay most
attention to is that of collections.
• Basic, core data structures.
• You’ll hear more about how these are internally implemented in
a later part of the module.
• The collection classes allow us to make use of
powerful, flexible data types without us having to
write them ourselves.
• There’s a considerable development burden in writing
objects that are genuinely reuseable.
Collections
• Much like an array, a collection holds a number of discreet
elements.
• Unlike an array, ordering cannot be assumed with many
collections.
• These classes are not designed to be base classes for
more specialised derived classes.
• Destructors for example are explictly designed to be non-virtual.
Collections
• Collections break down into three main
categories.
• Sequential, where order is maintained.
• List
• Vector
• Associative, where no order is guaranteed.
• Set
• Hash Map
• Adapter, which act as wrappers around other core
structures.
• Queue
• Stack
The Vector
• The Vector is defined in the std namespace.
• #include <vector> into your code.
• Vectors are resizeable arrays.
• You can just keep adding things in and they’ll expand to meet your
requirements.
• Basic structure for interacting with a vector is common to
all STL collections.
The Vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> *v = new vector<int>();
v->push_back (100);
v->push_back (200);
v->push_back (500);
for (int i = 0; i < v->size(); i++) {
cout << v->at (i) << endl;
}
return 0;
}
The Vector
• Useful methods:
• push_back – push an element to the back of the structure
• size – get the number of elements in the collection
• at – pull the element out at that specific position.
• Memory management of a container done during
accesses.
Vector Memory Management
• Two measures for collections are available.
• capacity – how many elements can the collection hold before new
space needs to be allocated.
• max_size – how many elements, in total, the collection can hold.
• Determined by the system.
• resize() and reserve() allow for fine-grained control over
capacity.
The List
• The list implements a doubly-linked list for traversal.
• Can go forwards and backwards.
• Basic structure for adding to a list the same as with a
vector.
• Can also push_front
• Traversal of the list done through an iterator.
• Possible for most of the STL classes.
Iterators
• Iterators are a common interface across container
classes.
• They represent an object that allows traversal through a collection.
• Obtained by using the following syntax:
• Collection<type>::iterator
• list<int>::iterator
• The iterator serves as the basis for more elegant output of
state date.
Iterators
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> *l = new list<int>();
list<int>::iterator i;
l->push_back (100);
l->push_front(200);
for (i = l->begin(); i != l->end(); i++) {
cout << *i << endl;
}
return 0;
}
Reversal Traversal
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> *l = new list<int>();
list<int>::reverse_iterator i;
l->push_back (100);
l->push_front(200);
for (i = l->rbegin(); i != l->rend(); i++) {
cout << *i << endl;
}
return 0;
}
Collections
• Most sequence collections also implement a sort function.
• Another time we need to overload an operator as part of C++
• < operator must be overloaded to permit sorting of custom objects
based on developer requirements.
• Many other useful functions available.
• Won’t cover these in the lecture – documentation available in many
places.
Algorithms
• STL also contains implementations for common
algorithms.
• Sort
• Searches
• Must #include <algorithm> to get access to methods.
• Many of these methods similarly require operators to be
overloaded.
• Curse you C++.
Vector with Iterator, Sort and
Search
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> *v = new vector<int>();
vector<int>::iterator i;
bool found;
v->push_back (200);
v->push_back (100);
v->push_back (500);
sort (v->begin(), v->end());
found = binary_search (v->begin(), v->end(), 200);
cout << "Value 200 found in Vector" << endl;
for (i = v->begin(); i < v->end(); i++) {
cout << *i << endl;
}
return 0;
}
Class Defined for Sorting
class Person {
private:
int age;
public:
Person();
Person (int x);
void set_age (int x);
int query_age();
bool operator< (Person &a);
};
Class Implementation
#include "Person.h"
Person::Person() :
age (18) {
}
Person::Person (int x) :
age (x) {
}
int Person::query_age() {
return age;
}
void Person::set_age (int na) {
age = na;
}
bool operator<(Person& a, Person& b) {
return a.query_age() < a.query_age();
}
Versus Java
• It seems like much more is needed to implement a C++
class for collections than in Java.
• The same amount of code is required for both.
• Java requires an implementation of compareTo.
• C++ requires an implementation of an overloaded < operator.
Why Use STL Classes?
• The STL classes are battle-hardened and battle-scarred
• They work.
• They make use of templates, and thus can handle any
appropriately defined object you devise.
• Most of the common data structures are available as part
of the STL.
Why Not Use Them?
• Well, no real reason not to…
• … for real code.
• Array manipulation exercises and data structure
creation are important ‘clarity’ topics.
• It’s always worth understanding how data structures are
implemented.
• Remember, C++ is all about how things are represented
internally.
• Best to learn how to ‘roll your own’ first.
• Then use the STL versions because they are more
complete.
Summary
• C++ provides implementations of most of the standard
data types.
• And also corresponding implementations of default operations such
as searchs and sorts.
• Vectors and lists permit the traversal of ordered data.
• Important to define user classes appropriately for sorting
and searching.

Contenu connexe

Tendances (20)

C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
An Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryAn Introduction to the C++ Standard Library
An Introduction to the C++ Standard 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
 
List
ListList
List
 
Priority Queue
Priority QueuePriority Queue
Priority Queue
 
Standard Library Functions
Standard Library FunctionsStandard Library Functions
Standard Library Functions
 
Sets
SetsSets
Sets
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Algorithms: I
Algorithms: IAlgorithms: I
Algorithms: I
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
 
Dynamic memory allocation and linked lists
Dynamic memory allocation and linked listsDynamic memory allocation and linked lists
Dynamic memory allocation and linked lists
 
C++ arrays part1
C++ arrays part1C++ arrays part1
C++ arrays part1
 
Arrays
ArraysArrays
Arrays
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Array ppt
Array pptArray ppt
Array ppt
 
Tools for reading papers
Tools for reading papersTools for reading papers
Tools for reading papers
 
L11 array list
L11 array listL11 array list
L11 array list
 

En vedette

An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL乐群 陈
 
E rate presentation
E rate presentationE rate presentation
E rate presentationcoacheller
 
2CPP10 - Polymorphism
2CPP10 - Polymorphism2CPP10 - Polymorphism
2CPP10 - PolymorphismMichael Heron
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator OverloadingMichael Heron
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method OverridingMichael Heron
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation FundamentalsMichael Heron
 
2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - InheritanceMichael Heron
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method OverloadingMichael Heron
 
2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented ProgramMichael Heron
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and PointersMichael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 

En vedette (20)

Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
E rate presentation
E rate presentationE rate presentation
E rate presentation
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
2CPP10 - Polymorphism
2CPP10 - Polymorphism2CPP10 - Polymorphism
2CPP10 - Polymorphism
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
C++primer
C++primerC++primer
C++primer
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
 
2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - Inheritance
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method Overloading
 
The STL
The STLThe STL
The STL
 
Sysprog 9
Sysprog 9Sysprog 9
Sysprog 9
 
2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers
 
2CPP02 - C++ Primer
2CPP02 - C++ Primer2CPP02 - C++ Primer
2CPP02 - C++ Primer
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Similaire à 2CPP16 - STL

Similaire à 2CPP16 - STL (20)

c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
 
Net framework
Net frameworkNet framework
Net framework
 
CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learning
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
DSA-Day-2-PS.pptx
DSA-Day-2-PS.pptxDSA-Day-2-PS.pptx
DSA-Day-2-PS.pptx
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 

Plus de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 
2CPP09 - Encapsulation
2CPP09 - Encapsulation2CPP09 - Encapsulation
2CPP09 - EncapsulationMichael Heron
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and OverridingMichael Heron
 

Plus de Michael Heron (18)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP09 - Encapsulation
2CPP09 - Encapsulation2CPP09 - Encapsulation
2CPP09 - Encapsulation
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding
 

Dernier

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Dernier (20)

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

2CPP16 - STL

  • 2. Introduction • The great promise of object orientation is reusability. • As of now, we haven’t done much re-using. • In the same way that Java provides comprehensive libraries of basic structures, so too does C++ • Through the mechanism of the Standard Template Library.
  • 3. Standard Template Library • The STL is not a part of the core C++ language. • It’s a set of extended libraries that have nearly ubiquitous applicability. • They are defined in the C++ standard. • It provides implementations of many of the standard data types available in other languages. • It is driven by the power of templates (as discussed in the previous lecture).
  • 4. Standard Template Library • The STL subset that we are going to pay most attention to is that of collections. • Basic, core data structures. • You’ll hear more about how these are internally implemented in a later part of the module. • The collection classes allow us to make use of powerful, flexible data types without us having to write them ourselves. • There’s a considerable development burden in writing objects that are genuinely reuseable.
  • 5. Collections • Much like an array, a collection holds a number of discreet elements. • Unlike an array, ordering cannot be assumed with many collections. • These classes are not designed to be base classes for more specialised derived classes. • Destructors for example are explictly designed to be non-virtual.
  • 6. Collections • Collections break down into three main categories. • Sequential, where order is maintained. • List • Vector • Associative, where no order is guaranteed. • Set • Hash Map • Adapter, which act as wrappers around other core structures. • Queue • Stack
  • 7. The Vector • The Vector is defined in the std namespace. • #include <vector> into your code. • Vectors are resizeable arrays. • You can just keep adding things in and they’ll expand to meet your requirements. • Basic structure for interacting with a vector is common to all STL collections.
  • 8. The Vector #include <iostream> #include <vector> using namespace std; int main() { vector<int> *v = new vector<int>(); v->push_back (100); v->push_back (200); v->push_back (500); for (int i = 0; i < v->size(); i++) { cout << v->at (i) << endl; } return 0; }
  • 9. The Vector • Useful methods: • push_back – push an element to the back of the structure • size – get the number of elements in the collection • at – pull the element out at that specific position. • Memory management of a container done during accesses.
  • 10. Vector Memory Management • Two measures for collections are available. • capacity – how many elements can the collection hold before new space needs to be allocated. • max_size – how many elements, in total, the collection can hold. • Determined by the system. • resize() and reserve() allow for fine-grained control over capacity.
  • 11. The List • The list implements a doubly-linked list for traversal. • Can go forwards and backwards. • Basic structure for adding to a list the same as with a vector. • Can also push_front • Traversal of the list done through an iterator. • Possible for most of the STL classes.
  • 12. Iterators • Iterators are a common interface across container classes. • They represent an object that allows traversal through a collection. • Obtained by using the following syntax: • Collection<type>::iterator • list<int>::iterator • The iterator serves as the basis for more elegant output of state date.
  • 13. Iterators #include <iostream> #include <list> using namespace std; int main() { list<int> *l = new list<int>(); list<int>::iterator i; l->push_back (100); l->push_front(200); for (i = l->begin(); i != l->end(); i++) { cout << *i << endl; } return 0; }
  • 14. Reversal Traversal #include <iostream> #include <list> using namespace std; int main() { list<int> *l = new list<int>(); list<int>::reverse_iterator i; l->push_back (100); l->push_front(200); for (i = l->rbegin(); i != l->rend(); i++) { cout << *i << endl; } return 0; }
  • 15. Collections • Most sequence collections also implement a sort function. • Another time we need to overload an operator as part of C++ • < operator must be overloaded to permit sorting of custom objects based on developer requirements. • Many other useful functions available. • Won’t cover these in the lecture – documentation available in many places.
  • 16. Algorithms • STL also contains implementations for common algorithms. • Sort • Searches • Must #include <algorithm> to get access to methods. • Many of these methods similarly require operators to be overloaded. • Curse you C++.
  • 17. Vector with Iterator, Sort and Search #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> *v = new vector<int>(); vector<int>::iterator i; bool found; v->push_back (200); v->push_back (100); v->push_back (500); sort (v->begin(), v->end()); found = binary_search (v->begin(), v->end(), 200); cout << "Value 200 found in Vector" << endl; for (i = v->begin(); i < v->end(); i++) { cout << *i << endl; } return 0; }
  • 18. Class Defined for Sorting class Person { private: int age; public: Person(); Person (int x); void set_age (int x); int query_age(); bool operator< (Person &a); };
  • 19. Class Implementation #include "Person.h" Person::Person() : age (18) { } Person::Person (int x) : age (x) { } int Person::query_age() { return age; } void Person::set_age (int na) { age = na; } bool operator<(Person& a, Person& b) { return a.query_age() < a.query_age(); }
  • 20. Versus Java • It seems like much more is needed to implement a C++ class for collections than in Java. • The same amount of code is required for both. • Java requires an implementation of compareTo. • C++ requires an implementation of an overloaded < operator.
  • 21. Why Use STL Classes? • The STL classes are battle-hardened and battle-scarred • They work. • They make use of templates, and thus can handle any appropriately defined object you devise. • Most of the common data structures are available as part of the STL.
  • 22. Why Not Use Them? • Well, no real reason not to… • … for real code. • Array manipulation exercises and data structure creation are important ‘clarity’ topics. • It’s always worth understanding how data structures are implemented. • Remember, C++ is all about how things are represented internally. • Best to learn how to ‘roll your own’ first. • Then use the STL versions because they are more complete.
  • 23. Summary • C++ provides implementations of most of the standard data types. • And also corresponding implementations of default operations such as searchs and sorts. • Vectors and lists permit the traversal of ordered data. • Important to define user classes appropriately for sorting and searching.