stl csse 250 susan reeder. what is the stl? standard template library standard c++ library is an...

30
STL STL CSSE 250 CSSE 250 Susan Reeder Susan Reeder

Upload: liliana-fitzgerald

Post on 17-Jan-2018

225 views

Category:

Documents


0 download

DESCRIPTION

Origins of STL With the popularity of C/C++, many companies found profit in providing libraries of routines designed to handle the storage and processing of data. ANSI/ISO added a standard for these libraries – the STL The STL brings a mature set of generic containers and algorithms to the C++ language that didn’t exist before.

TRANSCRIPT

Page 1: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

STLSTLCSSE 250CSSE 250

Susan ReederSusan Reeder

Page 2: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

What is the STL?What is the STL?

Standard Template LibraryStandard Template LibraryStandard C++ Library is an extensible Standard C++ Library is an extensible framework which contains components forframework which contains components for Language supportLanguage support DiagnosticsDiagnostics General utilitiesGeneral utilities StringsStrings LocalesLocales Standard template library (containers, iterators, Standard template library (containers, iterators,

algorithms, numerics)algorithms, numerics) Input/outputInput/output

Page 3: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Origins of STLOrigins of STL

With the popularity of C/C++, many With the popularity of C/C++, many companies found profit in providing companies found profit in providing libraries of routines designed to handle the libraries of routines designed to handle the storage and processing of data.storage and processing of data.ANSI/ISO added a standard for these ANSI/ISO added a standard for these libraries – the STLlibraries – the STLThe STL brings a mature set of generic The STL brings a mature set of generic containers and algorithms to the C++ containers and algorithms to the C++ language that didn’t exist before.language that didn’t exist before.

Page 4: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

What do you need to know?What do you need to know?

List of what is available (published in many List of what is available (published in many sources)sources)How to use itHow to use it Understand generic programmingUnderstand generic programming Understand templatesUnderstand templates Cross-platform Standard TemplatesCross-platform Standard Templates

Page 5: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Three “parts” of STLThree “parts” of STL

Conceptually, the STL encompasses three Conceptually, the STL encompasses three separate algorithmic problem solvers.separate algorithmic problem solvers. ContainersContainers AlgorithmsAlgorithms IteratorsIterators

Page 6: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

ContainersContainers

A way that stored data is organized in A way that stored data is organized in memorymemory Array, Stack, Queue, Linked list, Binary treeArray, Stack, Queue, Linked list, Binary treeImplemented by template classes to be Implemented by template classes to be customizablecustomizableAll have common management member All have common management member functionsfunctions Insert(), erase(), begin(), etc.Insert(), erase(), begin(), etc.Also have individual member functionsAlso have individual member functions

Page 7: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

AlgorithmsAlgorithms

Behaviors or functionality applied to Behaviors or functionality applied to containers to process their contents in containers to process their contents in various ways.various ways. Sort, copy, search, mergeSort, copy, search, merge

Template functions – not part of a class, Template functions – not part of a class, but a stand-alone functionbut a stand-alone functionCan be used on containers other than STL Can be used on containers other than STL (e.g. common arrays)(e.g. common arrays)

Page 8: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

IteratorsIterators

Once you have a container and an Once you have a container and an algorithm, an iterator will allow the two to algorithm, an iterator will allow the two to interact.interact.Iterator is a generalized pointer that points Iterator is a generalized pointer that points to elements within a container.to elements within a container.Iterators are a key part of the STL Iterators are a key part of the STL because they connect algorithms with because they connect algorithms with containers.containers.

Page 9: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Iterators, cont.Iterators, cont.

Iterators are objects that point to other objects.Iterators are objects that point to other objects.As objects, they have data members and As objects, they have data members and member functions.member functions.Iterators are central to generic programming Iterators are central to generic programming because they are an interface between because they are an interface between containers and algorithms; algorithms typically containers and algorithms; algorithms typically take iterators as arguments, so a container need take iterators as arguments, so a container need only supply a way to access its elements using only supply a way to access its elements using iterators.iterators.

Page 10: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Iterator ConceptsIterator Concepts

Input iteratorInput iterator Only guarantees read accessOnly guarantees read accessOutput iteratorOutput iterator Only guarantees write accessOnly guarantees write accessForward iteratorForward iterator Supports input/outputSupports input/output Can be constant or mutableCan be constant or mutable Supports “forward” motion through the Supports “forward” motion through the

container (increment)container (increment)

Page 11: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Iterator Concepts, cont.Iterator Concepts, cont.

Bidirectional iteratorBidirectional iterator Supports input/outputSupports input/output Can be constant or mutableCan be constant or mutable Supports increment or decrementSupports increment or decrement

Random Access iteratorRandom Access iterator Supports input/outputSupports input/output Allows random movement through containerAllows random movement through container

Page 12: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Iterator Concepts, cont.Iterator Concepts, cont.

Most algorithms are expressed not in Most algorithms are expressed not in terms of a single iterator, but in terms of a terms of a single iterator, but in terms of a range of iterators (first, last).range of iterators (first, last).A class needs to provide access for an A class needs to provide access for an iterator – either by returning one or making iterator – either by returning one or making the iterator class a friend.the iterator class a friend.

Page 13: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Latest Language UpdatesLatest Language Updates

Using namespaceUsing namespaceCasting changesCasting changesRTTI (Run-Time Type Information)RTTI (Run-Time Type Information)

Page 14: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

NamespaceNamespace

Namespaces control scope or identifier Namespaces control scope or identifier visibilityvisibilityTightest scope is local – those identifiers Tightest scope is local – those identifiers declared within a functiondeclared within a functionNext up would be class scopeNext up would be class scopeHighest level is program or workspace Highest level is program or workspace scopescope

Page 15: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Defining namespacesDefining namespaces

Encapsulate your declarations within a Encapsulate your declarations within a namespace blocknamespace block

namespace your_namespace_name{namespace your_namespace_name{ int ivalue;int ivalue; class my_class {….};class my_class {….}; // more declarations;// more declarations;}}

Page 16: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

How to useHow to use

Any code statements within Any code statements within your_namespace_name have direct access to your_namespace_name have direct access to the namespace’s declarationsthe namespace’s declarationsCode statements outside of Code statements outside of your_namespace_name must use qualifying your_namespace_name must use qualifying syntaxsyntax

int main()int main(){ your_namespace_name::ivalue++;{ your_namespace_name::ivalue++;……..}}

Page 17: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

How to useHow to use

Using statement removes the need to qualify, Using statement removes the need to qualify, but allows global access to everything in the but allows global access to everything in the listed namespace.listed namespace.

using namespace your_namespace_name;using namespace your_namespace_name;the Selective using statement is somewhere the Selective using statement is somewhere between fully qualified and global accessbetween fully qualified and global access

using your_namespace_name::ivalue;using your_namespace_name::ivalue;each allows access to ivalue without each allows access to ivalue without another qualifying syntaxanother qualifying syntax

Page 18: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

RenamingRenaming

Long namespace names help with scope, Long namespace names help with scope, but can be unwieldy.but can be unwieldy.

namespace YNN = namespace YNN = your_namespace_name;your_namespace_name;Can also have unnamed namespacesCan also have unnamed namespaces compiler will internally provide name, but the compiler will internally provide name, but the

identifiers are only available within the identifiers are only available within the defining filedefining file

simply leave out the name in the definitionsimply leave out the name in the definition

Page 19: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

CastingCasting

Dynamic castingDynamic casting used to convert a base class pointer or used to convert a base class pointer or

reference to a derived class pointer or reference to a derived class pointer or reference – checked at run timereference – checked at run time

dynamic_cast <castType>(objectToCast);dynamic_cast <castType>(objectToCast);Static castingStatic casting used to convert between types that are not in used to convert between types that are not in

the same class hierarchy – checked at the same class hierarchy – checked at compile timecompile time

static_cast<castType>(objectToCast);static_cast<castType>(objectToCast);

Page 20: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

RTTIRTTI

Run-Time Type InformationRun-Time Type Informationmust include <typeinfo> librarymust include <typeinfo> libraryuse the typeid operator to get the type of use the typeid operator to get the type of any objectany objectcan be used for debugging or simply can be used for debugging or simply verifying the objects in use at any time as verifying the objects in use at any time as a useful piece of run-time logic controla useful piece of run-time logic control

Page 21: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard C++ LibraryStandard C++ Library

C++ Language SupportC++ Language Support the basic typesthe basic types dynamic memory allocationdynamic memory allocation exception processingexception processing

Diagnostic ToolsDiagnostic Tools assertions & error codesassertions & error codes

General C/C++ UtilitiesGeneral C/C++ Utilities components used by other elementscomponents used by other elements

Page 22: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard C++ LibraryStandard C++ Library

StringsStrings components for manipulating sequences of components for manipulating sequences of

characters – type char, w_char (UNICODE) or characters – type char, w_char (UNICODE) or a type defined in a programa type defined in a program

Cultural Formatting SupportCultural Formatting Support numeric, monetary and date/time formatting numeric, monetary and date/time formatting

and parsingand parsingSTL (Standard Template Library)STL (Standard Template Library) containers, algorithms, iteratorscontainers, algorithms, iterators

Page 23: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard C++ LibraryStandard C++ Library

Advanced Numerical ComputationAdvanced Numerical Computation seminumerical operations and components for seminumerical operations and components for

complex number types, numeric arrays, and complex number types, numeric arrays, and generalized numeric algorithmsgeneralized numeric algorithms

Input/OutputInput/Output components for iostreamscomponents for iostreams

Standard C LibraryStandard C Library incorporates the Standard C Libraryincorporates the Standard C Library

Page 24: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard C++ Library HeadersStandard C++ Library Headers

algorithmalgorithm cmathcmathbitsetbitset complexcomplexcassertcassert csetjmpcsetjmpcctypecctype csignalcsignalcerrnocerrno cstdargcstdargcfloatcfloat cstddefcstddefciso646ciso646 cstdiocstdioclimitsclimits cstdlibcstdlibclocaleclocale cstringcstring

Page 25: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard C++ Library HeadersStandard C++ Library Headers

ctimectime iosfwdiosfwdcwcharcwchar iostreamiostreamcwctypecwctype istreamistreamdequedeque iteratoriteratorexceptionexception limitslimitsfstreamfstream listlistfunctionalfunctional localelocaleiomanipiomanip mapmapiosios memorymemory

Page 26: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard C++ Library HeadersStandard C++ Library Headers

newnew stringstringnumericnumeric strstream ??strstream ??ostreamostream typeinfotypeinfoqueuequeue utilityutilitysetset valarrayvalarraysstreamsstream vectorvectorstackstackstdexceptstdexceptstreambufstreambuf

Page 27: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Standard Template LibraryStandard Template Library

Containers, algorithms, iteratorsContainers, algorithms, iteratorsIndividual STL libraries and “glue” Individual STL libraries and “glue” components are designed to work together components are designed to work together in useful ways to produce the kind of in useful ways to produce the kind of larger and more specialized algorithms larger and more specialized algorithms needed in today’s applicationsneeded in today’s applications

Page 28: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Rules for using STLRules for using STL

Create objects to use with STL containersCreate objects to use with STL containersMake sure objects includeMake sure objects include A copy constructorA copy constructor An assignment operator, =An assignment operator, = An equality comparison operator, ==An equality comparison operator, == A less than comparison operator, <A less than comparison operator, <

Or can use existing typesOr can use existing types

Page 29: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

An exampleAn example

vector<int> v(3); // declares vector size 3vector<int> v(3); // declares vector size 3v[0] = 7;v[0] = 7;v[1] = v[0] + 3;v[1] = v[0] + 3;v[2] = v[0] + v[1]; v[2] = v[0] + v[1]; // v[0] == 7, v[1] == 10, v[2] = 17// v[0] == 7, v[1] == 10, v[2] = 17

reverse(v.begin(), v.end());reverse(v.begin(), v.end()); // v[0] == 17, v[1] == 10, v[2] = 7// v[0] == 17, v[1] == 10, v[2] = 7

Page 30: STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language

Final wordFinal word

Possible to write code and never need to Possible to write code and never need to actually create own data structuresactually create own data structuresMost languages do not provide these Most languages do not provide these types of librariestypes of librariesSometimes using the STL bloats your Sometimes using the STL bloats your program and makes it inefficientprogram and makes it inefficientGood to know how to write your own, then Good to know how to write your own, then there are optionsthere are options