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

Post on 17-Jan-2018

225 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

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

STLSTLCSSE 250CSSE 250

Susan ReederSusan Reeder

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

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.

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

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

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

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)

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.

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.

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)

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

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.

Latest Language UpdatesLatest Language Updates

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

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

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;}}

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++;……..}}

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

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

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);

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

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

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

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

Standard C++ Library HeadersStandard C++ Library Headers

algorithmalgorithm cmathcmathbitsetbitset complexcomplexcassertcassert csetjmpcsetjmpcctypecctype csignalcsignalcerrnocerrno cstdargcstdargcfloatcfloat cstddefcstddefciso646ciso646 cstdiocstdioclimitsclimits cstdlibcstdlibclocaleclocale cstringcstring

Standard C++ Library HeadersStandard C++ Library Headers

ctimectime iosfwdiosfwdcwcharcwchar iostreamiostreamcwctypecwctype istreamistreamdequedeque iteratoriteratorexceptionexception limitslimitsfstreamfstream listlistfunctionalfunctional localelocaleiomanipiomanip mapmapiosios memorymemory

Standard C++ Library HeadersStandard C++ Library Headers

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

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

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

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

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

top related