Standard Template Library

Slides:



Advertisements
Similar presentations
Data Structures Using C++ 2E
Advertisements

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
More on the STL vector list stack queue priority_queue.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Templates and the STL.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
Data Structures Using C++ 2E
Containers Overview and Class Vector
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
C++ STL CSCI 3110.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
C++ Review STL CONTAINERS.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Pointers and Linked Lists
Pointers and Linked Lists
Programming with ANSI C ++
Standard Template Library
C++ Templates.
Motivation and Overview
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Templates in C++.
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Templates ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY.
10 – Iterators C++ Templates 4.6 The Iterator pgs
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
ADT Implementations: Templates and Standard Containers
Object Oriented Programming COP3330 / CGS5409
CS212: Object Oriented Analysis and Design
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
priority_queue<T>
Lists - I The List ADT.
Lists - I The List ADT.
Iterators and STL Containers
Lecture 8 : Intro. to STL (Standard Template Library)
Parasol Lab, Texas A&M University
Lab4 problems More about templates Some STL
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
An Introduction to STL.
Chapter 3 Lists, Stacks, and Queues
SPL – PS1 Introduction to C++.
Standard Template Library
Presentation transcript:

Standard Template Library An Overview of the Standard Template Library CSCE 221, Texas A&M University Adapted from RebootSoft http://www.rebootsoft.com/Presentations/stl/STL.zip

Overview of the STL What is the STL ? History of the STL C++ Templates 101 STL Components Containers Algorithms Iterators Allocators, Function Objects & Adaptors The Container Classes & Hierachy The Vector Class Summary of this Presentation… Aim of presentation: Give an understanding of the Standard Template Library Look at the architecture and main elements the make up the STL Walk through some simple code examples Provide links to more information Please do not: Start a religious battle about merrits of C and C++ There are newsgroups for that ! 2

What is the STL ? Part of the Standard C++ library Set of C++ template classes and functions Implements many common: Data structures E.g. lists and queues Algorithms E.g. sorting and searching Can be applied to nearly any type of data Developed by CS professionals over years Many compilers now support it MS VC6, Borland C++, gcc, etc. Part of the ANSI standard for C++ It consists of a set of C++ template classes and functions Implements many common: Data structures E.g. lists and queues Algorithms E.g. sorting and searching Can be applied to nearly any type of data It provides basic building blocks for your C++ programs Many compilers now support it MS VC6, Borland C++, gcc MS VC5 does not fully implement the standard. 3

History of the STL Brainchild of Alexander Stepanov 1979 initial research into generic programming Much of the work done when Stepanov worked at HP Early work was done on C and Ada 1987 produced a generic Ada library However Stepanov realized that STL best suited C++ 1990 the implementation language was changed to C++ 1994 ISO committee voted to include STL into C++ 1995 HP reference implementation released on the internet Brainchild of Alexander Stepanov Project was began in 1979 (as initial research into generic programming) Early work was done on C and Ada but either of these languages supported all the features that the STL’s final architecture required. However, these features were being incorporated into C++ In late 1993 Stepanov gave a informal talk to the ANSI C++ committee on STL In mid 1994 committee voted to include STL into C++ standard The inclusion slowed the standardization of C++, but increased the scope and power of the language. 4

C++ Templates 101 Templates are not types, but rather they are a placeholder for a type C++ templates come in two flavors: Functions templates Class templates Next few slides are just a refresher for C++ templates: Templates are not types, but rather they are a placeholder for a type C++ templates come in two flavors: Functions templates Class templates 5

C++ Templates 101 Functions templates used to define generic algorithms. While this is useful, it only works for integers. A better solution is to define a function template for max int max(int x, int y) { return x < y ? y : x; } Template functions have the following form: template < template-argument-list > function-definition The template-argument-list is one or more type-names within the scope of the template definition. In template functions the first argument is always a type. template <class T> T max(T x, T y) { return x < y ? y : x; } 6

C++ Templates 101 Nothing special has to be done to use a function template Note: all that is required of the type passed to max is the comparison operator, operator<. int main(int argc, char* argv[]) { int a = 3, b = 7; double x = 3.14, y = 2.71; cout << max(a, b) << endl; // Instantiated with type int cout << max(x, y) << endl; // Instantiated with type double cout << max(a, x) << endl; // ERROR: types do not match } SHOW PREVIOUS PAGE AS FOIL Nothing special has to be done to use a function template No special libraries or header files required. The compiler examines the types of the arguments and instantiates the appropriate function for you. For this example, we are only using the built-in types (e.g. int and double), so the C++ language defines the ‘less-than’ operator. SHOW EXAMPLE ( func_template1 ) 7

C++ Templates 101 Class Templates May contain data member objects of any type. template <class T> class myarray { public: T* v; int sz; myarray(int s) { v = new T [sz = s]; } // Constructor ~myarray() { delete[] v; } // Destructor T& operator[] (int i) { return v[i]; } void set(int i, T val) { v[i] = val; } int size() { return sz; } }; Class Templates Just as a function template is able to take argument of any type, a class template may contain (as its data members) objects of any type.  class myarray You can instantiate different widget-containers which store objects of different types: myarray<int> iwidget(10); myarray<char> cwidget(10); myarray<shape> swidget(10); Take a look at the notation, the type-name is myarray<specific_type>. Then instantiate the same container with objects of different types: myarray<int> iwidget(10); myarray<shape> swidget(10); 8

STL Components Adaptors Containers Allocators Iterators Generic TRANSFORMS PROVIDE STORAGE FOR TRANSFORMS ACCESS APPLIED TO Iterators Generic Algorithms USE USE ASSIST This diagram shows a notional relationship. The STL is organized around 3 core components (shown in green): Containers Algorithms Iterators The STL uses 3 other components for support (shown in yellow): Allocators Adaptors Function objects At the core of the STL are containers Containers can be thought of as a box, that object get placed into Iterators are a way of pointing at objects in the box Algorithms perform operations on the objects in the box Basically algorithms have been decoupled from the container So that algorithms can only interact with a container via an iterator. Function Objects TRANSFORMS Simply put: Algorithms act on Containers through Iterators. 9

Containers Containers are objects that hold other objects There are 2 main types of container: Sequence Containers vector deque list Associative Containers Each container defines function that are meaningful to it. list container defines functions to insert & delete stack container defines functions to push and pop map set multimap multiset Containers are objects that hold other templated objects. There are 2 main types of container: Sequence Containers vector, deque & list Called Sequence Containers because in STL terminology, a sequence is a linear list. Associative Containers map, multimap, set, multiset Allow efficient retrieval of values based on keys. For example map provides access to values based on unique keys. So it stores a key/value pair and retrieves a value given its key. Each container defines function that are meaningful to it. List container defines functions to insert & delete Stack container defines functions to push and pop 10

Algorithms Algorithms act on Containers BUT Algorithms are decoupled from specific containers Capabilities include Initialization Sorting Searching Many algorithms can operate on a range of elements within a container. Algorithms Iterators Containers Algorithms act on Containers in order to manipulate its contents. BUT its important to remember: algorithms have been decoupled from the container they only interact with a container via an iterator Capabilities include: Initialization Sorting Searching Many algorithms can operate on a range of elements within a container. 11

Iterators Iterators are objects that act like pointers. Provide the ability to cycle through the contents of a container. There are 5 types of iterator: Random access Bidirectional Forward Input Output Iterators are handled liked pointers i.e. You can increment and decrement them. You can apply the * operator to them. Random access (More general) Bidirectional Forward Iterators are objects that act like pointers Provide the ability to cycle through the contents of a container. In much the same way you would use a pointer to cycle through and array. The STL provides a hierarchy of 5 iterator types: Random access Store and retrieve values. Access elements randomly. Bidirectional Store and retrieve values. Forward and backward moving. Forward Store and retrieve values. Forward moving only. Input Retrieve but not store values. Forward moving only. Output Store but not retrieve values. Forward moving only. Iterators are handled liked pointers i.e. You can increment and decrement them & apply the * operator to them (dereference). Input Output (More restrictive) 12

Allocators, Function Objects & Adaptors Manage memory for Containers In most cases the default Allocator is sufficient However its available if you wanted you do you own memory management Function Objects Function objects are classes that define operator() Several predefined function, less(), greater(), plus() They can be used in place of function pointers in STL algorithms Adaptors An Adaptor transforms one thing into another There are Container adaptors, Iterator adaptors & Function adaptors Example of a container adaptor is queue This adapts a the deque container for use a standard queue. Allocators Allocators are an attempt to address portability of the C++ Library to different machine architectures. One of the main problems to address in portability is the memory model of the machine. (tiny -> flat) Allocators encapsulate information about the machines memory model, e.g. information about pointer types, the size of objects which primitives are used to allocate and deallocate raw memory Thus they separate the STL from the dependencies of the underlying memory model of the machine architecture. 13

The Container Classes Container Description Required Header deque A double ended queue <deque> list A linear list <list> map Stores key/value pairs <map> multimap multiset A set in which each element may not be unique <set> priority_queue A priority queue <queue> queue A queue set A set of unique elements stack A stack <stack> vector A dynamic array <vector> Containers are the core of the STL. Containers are implemented using template classes. Sequence Containers (RED) vector, list & deque Sequence containers operate on sequences, which are essentially linear lists of objects. Associative Containers (GREEN) map, multimap, set & multiset Associative containers operate on lists of key/value pairs and allow the retrieval of a value given its key. Container Adaptors (BLUE) stack, queue & priority_queue Called container adaptors because they use (adapt) one of the sequence containers to hold their elements. Thus one of the sequence containers underlies the functionality provided by stack, queue & priority_queue. From a programmers view a container adaptor looks much like a normal container. Sequence Containers , Associative Containers , Container Adaptors 14

The Container Hierarchy Collections Containers Adaptors Sequence Associative Colours show which functions are common across different containers. 15

Sequence Containers Three types of sequence containers in STL They store data in linear sequence. vector deque list To choose a container: Operation vector deque list Access 1st element constant Access last Element Access "random" element Linear Add/Delete at Beginning Add/Delete at End Add/Delete at "random" There are three types of sequence containers in the STL. These, as their name suggests, store data in linear sequence. They are the vector, deque and list. To choose a container: decide what sort of operations you will most frequently perform on your data, then use the following table to help you. constant time is obviously better than linear time. Vector Using the vector as an example A vector is able to access elements at any position ("random" access) with a constant time overhead, O(1). Insertion or deletion at the end of a vector is "cheap". Insertions and deletions anywhere other than at the end of the vector incur overhead O(N), N being the number of elements in the vector, because all the following entries have to be shuffled along to make room for the new entries, the storage being contiguous 16

The vector Container One of the most commonly used containers Composed of a single block of sequential memory Supports a dynamic array Use when objects are inserted/removed primarily at the end Vectors template specification is: template <class T, class Allocator = allocator<T> > class vector T is the type of data being stored Allocator specifies the allocator The vector Class One of the most commonly used containers Composed of a single block of sequential memory Supports a dynamic array allocates memory on the fly so that you can grow and shrink the array as needed. Use when objects are inserted/removed primarily at the end Inefficiency: Overflow condition can cause a complete copy. Template specification is: template <class T, class Allocator = allocator<T> > class vector T is the type of data being stored Allocator specifies the allocator (which defaults to the standard allocator). Looking at the examples : Nothing complex about declaring vector You can see there are a number of different constructors which handle the different methods to declare the vector class. vector<char> cv1; // create zero-length char vector vector<int> iv1(10); // create 10 element int vector vector<char> cv2(5, ‘a’); // initialize a 5 element char vector vector<int> iv2(iv1); // create int vector from an int vector 17

The vector Class member functions Description iterator begin() Returns an iterator to the first element in the vector. iterator end() Returns an iterator to the end of the vector. bool empty() Returns true if the vector contains no elements. iterator erase(iterator i) Removes the element pointed to by i. Iterator insert(iterator i, constT &v) Inserts v immediately before element specified by i void pop_back() Removes the last element in the vector. void push_back(const T&v) Adds element with value v to the end of the vector. size_type size() Returns the number of elements in the vector. operator[] Access vector elements using standard array subscripting notation. ==, <, <=, !=, >, >= Comparison operators are defined for vector. Table shows a few of the the vector classes member functions: begin( ) – returns an iterator which points to the last element on the container. end( ) – returns an iterator which points to one past the last element in the container. Thus the last element in the container is end() – 1 insert( ) – No bounds checking is performed when you use operator []. 18

Using the vector Container Example: vector1 vector<int> v(10); // create vector of length 10 printf(“Size = %i\n”, v.size() ); // display original size for(i=0; i<10; i++) v[i] = i; // Assign elements values for(i=0; i<10; i++) printf(“%i “, v[i] ); // display elements for(i=0; i<5; i++) // Add 5 elements to vector v.push_back(i+10); printf(“New size = %i\n”, v.size() ); // display new size for(i=0; i<10; i++) v[i] = -v[i]; // Change element values NOTE: The size of vector can only be increased using push_back() or insert() It can NOT be increased by using the normal array subscription notation vector<int> v(10) v[12] = 10; // wrong OUTPUT: Size = 10 0 1 2 3 4 5 6 7 8 9 New size = 15 19

Using the vector iterator Example: vector3 vector<int> v; for(i=0; i<10; i++) v.push_back(i); // Assign 10 new elements vector<int>::iterator p = v.begin(); while( p != v.end() ) { printf("%i ", *p ); // Print elements forwards p++; } p = v.end(); while( p != v.begin() ) { p--; printf("%i ", *p ); // Print elements backwards The previous example used the standard array indexing to access the containers elements e.g. v[3]=10 In this example we are going to use iterator instead. An empty vector container is declared (with an integer template). Create 10 new elements with values 0…9 Declare an iterator p assign it to point to the 1st element in the container Forwards Loop until we go one element past the end of the container. *p acts like a normal dereferenced pointer would and returns the value of the element its currently ‘pointing’ at. Backwards assign the iterator to the end of the container loop while its not equal to the begin() iterator this time be sure to decrement the iterator first before printing the elements value. Print elements forwards: 0 1 2 3 4 5 6 7 8 9 Print elements backwards: 9 8 7 6 5 4 3 2 1 0 20