The Standard Template Library provides the framework for building generic, highly reusable algorithms and data structures A reference implementation of.

Slides:



Advertisements
Similar presentations
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library The standard template library (STL) contains Containers Algorithms Iterators A container is a way that stored data is organized.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Standard Containers: Vectors
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.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementations:
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
C++ fundamentals.
1 Read § vector begin() end() sort(). 2 Templates Templates allow functions and classes to be parameterized so that the type of data being operated.
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
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:
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Containers Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
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.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementations:
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
1 Read § Templates Templates allow functions and classes to be parameterized so that the ______________ data being operated upon (or stored)
1 Read § Templates Templates allow functions and classes to be _________________ so that the Templates provide a means to ________________—
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
 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.
Adapted from Data Structures with C++ using STL: Ford, Topp CS 362: Queues Dr. Nazli Mollah Overview of Lecture  Introduction  The Queue ADT  The Radix.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
The Standard Template Library Container Classes Version 1.0.
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.
1 The Standard Template Library Drozdek Section 3.7.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
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.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
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.
1 Designing Efficient Libraries Alexander Stepanov July 21, 2003 Alexander Stepanov July 21, 2003.
Object-Oriented Programming (OOP) Lecture No. 41
C++ Templates.
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
ADT Implementations: Templates and Standard Containers
Templates and Standard Containers
Standard Template Library
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Introduction to Data Structure
Standard Template Library
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
Standard Template Library
Presentation transcript:

The Standard Template Library provides the framework for building generic, highly reusable algorithms and data structures A reference implementation of STL has been put into the public domain by Hewlett-Packard Bjarne Stroustrup AT&T : "large, systematic, clean, formally sound, comprehensible, elegant, and efficient framework” Pamela Seymour Leiden University: "STL looks like the machine language macro library of an anally retentive assembly language programmer"

Design goals Generality + Efficiency Well structured, comprehensive library of useful components Every component is as abstract as theoretically possible and as efficient as its hand-coded, non-abstract version in C

Alexander Stepanov (BYTE 1995) The past 25 years have seen attempts to revolutionize programming by reducing all programs to a single conceptual primitive. Functional programming, for example, made everything into a function; the notions of states, addresses, and side effects were taboo. Then, with the advent of object-oriented programming (OOP), functions became taboo; everything became an object (with a state). STL is heavily influenced by both functional programming and OOP. But it's not a single-paradigm library; rather, it's a library for general- purpose programming of von Neumann computers. STL is based on an orthogonal decomposition of component space. For example, an array and a binary search should not be reduced to a single, fundamental notion. The two are quite different. An array is a data structure -- a component that holds data. A binary search is an algorithm -- a component that performs a computation on data stored in a data structure. As long as a data structure provides an adequate access method, you can use the binary-search algorithm on it.

Standard Template Library (STL) n object oriented programming - reuse, reuse, reuse u STL has many reusable components u Divided into F containers F iterators F algorithms n This is only an introduction to STL, a huge class library

Algorithms Container Classes STL (Standard Template Library) A library of class and function templates based on work in generic programming done by Alex Stepanov and Meng Lee of the Hewlett Packard Laboratories in the early 1990s. It has three components: 1. Containers: Generic "off-the-shelf" class templates for storing collections of data 2. Algorithms: Generic "off-the-shelf" function templates for operating on containers 3. Iterators: Generalized "smart" pointers that allow algorithms to operate on almost any container vector sort() begin() end() Iterators

vector begin() end() sort() containers algorithms iterators Standard Template Library (STL) class libraries function libraries class templates classes function templates data types user-defined (enums, structs, etc.) Data + Algorithms = Programs overloaded functions specific functions inline Code The Evolution of Reusability/Genericity

Containers, Iterators, Algorithms Container Algorithm Iterator Container Iterator Algorithm Objects Iterator Algorithm Algorithms use iterators to interact with objects stored in containers

STL's Containers In 1994, STL was adopted as a standard part of C++. There are 10 containers in STL: Kind of ContainerSTL Containers Sequential: deque, list, vector Associative: map, multimap, multiset, set Adapters: priority_queue, queue, stack Non-STL: bitset, valarray, string

Organizacja STL (2)

Organizacja STL (3)

Organizacja STL (4)

Organizacja STL (5)

Organizacja STL (6)

vector Operations Constructors: vector v, // empty vector v1(100), // contains 100 elements of type T v2(100, val), // contains 100 copies of val v3(fptr,lptr); // contains copies of elements in // memory locations fptr up to lptr Copy constructor Destructor v.capacity() Number of elements v can contain without growing v.max_size() Upper limit on the size and capacity v.size() Number of elements v actually contains v.reserve(n) Increase capacity (but not size) to n v.empty() Check if v is empty v.push_back(val) Add val at end v.pop_back() Remove value at end v.front(), v.back(),Access first value, last value, v[i], v.at(i)i -th value without / with range checking ( at throws out-of-range exception) Relational operatorsLexicographic order is used Assignment ( = )e.g., v1 = v2; v.swap(v1) Swap contents with those of vector v1

Iterators Iterators are similar to pointers –point to first element in a container –iterator operators uniform for all containers * dereferences, ++ points to next element begin() returns iterator pointing to first element end() returns iterator pointing to last element –use iterators with sequences (ranges) containers input sequences - istream_iterator output sequences - ostream_iterator

Iterators vector array_ n Iterators are pointer-like entities that are used to access individual elements in a container. n Often they are used to move sequentially from element to element, a process called iterating through a container size_ 4 vector ::iterator The iterator corresponding to the class vector is of the type vector ::iterator

The other operations require knowledge of iterators. For example: v.begin() Returns iterator positioned at first element v.end() Returns iterator positioned immediately after last element v.insert(it, val) Inserts val at position specified by iterator it v.erase(it) Removes the element at position specified by iterator it Note: insert() moves all the elements from position it and following one position to the right to make room for the new one. erase() moves all the elements from position it and following one position to the left to close the gap. An iterator declaration for vector s has the form: vector ::iterator it; for (vector ::iterator it or using an iterator: Example: Function to display the values stored in a vector of double s: ostream & operator & v) { for (int i = 0; i < v.size(); i++) out << v[i] << " "; return out; } = v.begin(); it++) out << *it << " "; it != v.end(); template T T Go to 54 Iterators – generalized pointers

Przykład – vector (1)

Przykład – vector (2)

Przykład – vector (3)

Przykład – vector (4)

Przykład – vector (5)

Przykład – vector (6)

Przykład – vector (7)

vector inefficiences When its capacity must be increased,  it must copy all the objects from the old vector to the new vector.  it must destroy each object in the old vector.  a lot of overhead! With deque this copying, creating, and destroying is avoided. Once an object is constructed, it can stay in the same memory locations as long as it exists (if insertions and deletions take place at the ends of the deque). Unlike vector s, a deque is not stored in a single varying-sized block of memory, but rather in a collection of fixed-size blocks (typically, 4K bytes). One of its data members is essentially an array map whose elements point to the locations of these blocks.

STL’s stack container STL includes a stack container. Actually, it is an adapter, as indicated by the fact that one of its type parameters is a container type. Sample declaration: stack > st; Basically, it is a class that acts as a wrapper around another class, providing a new user interface for that class. A container adapter such as stack uses the members of the encapsulated container to implement what looks like a new container. For a stack >, C may be any container that supports push_back() and pop_back() in a LIFO manner. In particular C may be a vector, a deque, or a list.

Constructor stack > st; creates an empty stack st of elements of type T ; it uses a container C to store the elements. Note 1: The space between the two > s must be there to avoid confusing the compiler (else it treats it as >> ); for example, stack > s; not stack > s; Note 2: The default container is deque ; that is, if C is omitted as in stack st; a deque will be used to store the stack elements. Thus stack st; is equivalent to stack > st; Destructor Assignment, relational Operators size(), empty(), top(), push(), pop() Basic Operations

STL's queue container In queue >, container type C may be list or deque. Why not vector ? You can't remove from the front efficiently! The default container is deque. queue has same member functions and operations as stack except: push() adds item at back (our addQ() ) front() (instead of top() ) retrieves front item pop() removes front item (our removeQ() ) back() retrieves rear item

queue Example

Contd.

As an ADT, a deque — an abbreviation for double-ended queue — is a sequential container that functions like a queue (or a stack) on both ends. It is an ordered collection of data items with the property that items can be added and removed only at the ends. Basic operations are: Construct a deque (usually empty): Check if the deque is empty Push_front: Add an element at the front of the deque Push_back: Add an element at the back of the deque Front:Retrieve the element at the front of the deque Back: Retrieve the element at the back of the deque Pop_front:Remove the element at the front of the deque Pop_back:Remove the element at the back of the deque Deques

STL's deque Class Template Has the same operations as vector except that there is no capacity() and no reserve() Has two new operations: d. push_front(value); Push copy of value at front of d d. pop_front(value); Remove value at the front of d Like STL's vector, it has several operations that are not defined for deque as an ADT: [] insert and delete at arbitrary points in the list, same kind of iterators. But insertion and deletion are not efficient and, in fact, take longer than for vector s.

vector vs. deque Capacity of a vector must be increased  it must copy the objects from the old vector to the new vector  it must destroy each object in the old vector  a lot of overhead! With deque this copying, creating, and destroying is avoided. Once an object is constructed, it can stay in the same memory locations as long as it exists (if insertions and deletions take place at the ends of the deque ). Unlike vector s, a deque isn't stored in a single varying-sized block of memory, but rather in a collection of fixed-size blocks (typically, 4K bytes). One of its data members is essentially an array map whose elements point to the locations of these blocks.

Algorithms Before STL –class libraries were incompatible among vendors –algorithms built into container classes STL separates containers and algorithms –easier to add new algorithms –more efficient, avoids virtual function calls STL provides algorithms used generically across containers –operate on elements indirectly through iterators –often operate on sequences of elements defined by pairs of iterators –algorithms often return iterators, such as find() –premade algorithms save programmers time and effort

STL algorithms

STL's algorithms (§7.5) Another major part of STL is its collection of more than 80 generic algorithms. They are not member functions of STL's container classes and do not access containers directly. Rather they are stand-alone functions that operate on data by means of iterators. This makes it possible to work with regular C-style arrays as well as containers. We illustrate one of these algorithms here: sort. Sort 1: Using < #include #include using namespace std; // Add a Display() template for arrays template void Display(ElemType arr, int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } int main() { int ints[] = {555, 33, 444, 22, 222, 777, 1, 66}; // must supply start and "past-the-end" pointers sort(ints, ints + 8); cout << "Sorted list of integers:\n"; Display(Ints, 8);

double dubs[] = {55.5, 3.3, 44.4, 2.2, 22.2, 77.7, 0.1}; sort(dubs, dubs + 7); cout << "\nSorted list of doubles:\n"; Display(Dubs, 7); string strs[] = {"good","morning","cpsc","186","class"}; sort(strs, strs + 5); cout << "\nSorted list of strings:\n"; Display(strs, 5); } Output: Sorted list of integers: Sorted list of doubles: Sorted list of strings: 186 class cpsc good morning

Sorting a vector of stacks using < (defined for stacks) #include using namespace std; #include "StackT.h" /* Add operator<() to our Stack class template as a member function with one Stack operand or as a friend function with two Stacks as operands. Or because of how we're defining < for Stacks here, st1 < st2 if top of st1 < top of st2 we can use the top() access function and make operator<() an ordinary function */ template bool operator & a, const Stack & b) { return a.top() < b.top();}

int main() { vector > st(4); // vector of 4 stacks of ints st[0].push(10); st[0].push(20); st[1].push(30); st[2].push(50); st[2].push(60); st[3].push(1); st[3].push(999); st[3].push(3); sort(st.begin(), st.end()); for (int i = 0; i < 4; i++) { cout << "Stack " << i << ":\n"; st[i].display(); cout << endl; } Output Stack 0: Stack 1: Stack 2: 30 Stack 3: 60 50

For_Each() Algorithm #include void show(int n) { cout << n << ” ”; } int arr[] = { 12, 3, 17, 8 }; // standard C array vector v(arr, arr+4); // initialize vector with C array for_each (v.begin(), v.end(), show); // apply function show // to each element of vector v

Function Objects function objects- contain functions invoked off the object using operator ()  header

Functions Objects n Some algorithms like sort, merge, accumulate can take a function object as argument. n A function object is an object of a template class that has a single member function : the overloaded operator () n It is also possible to use user-written functions in place of pre-defined function objects #include int arr1[]= { 6, 4, 9, 1, 7 }; list l1(arr1, arr1+5); // initialize l1 with arr1 l1.sort(greater ()); // uses function object greater // for sorting in reverse order l1 = { 9, 7, 6, 4, 1 }

Function Objects n The accumulate algorithm accumulates data over the elements of the containing, for example computing the sum of elements #include int arr1[]= { 6, 4, 9, 1, 7 }; list l1(arr1, arr1+5); // initialize l1 with arr1 int sum = accumulate(l1.begin(), l1.end(), 0, plus ()); int sum = accumulate(l1.begin(), l1.end(),0); // equivalent int fac = accumulate(l1.begin(), l1.end(), 0, times ());

User Defined Function Objects class squared _sum // user-defined function object { public: int operator()(int n1, int n2) { return n1+n2*n2; } }; int sq = accumulate(l1.begin(), l1.end(), 0, squared_sum() ); // computes the sum of squares

User Defined Function Objects template class squared _sum // user-defined function object { public: T operator()(T n1, T n2) { return n1+n2*n2; } }; vector vc; complex sum_vc; vc.push_back(complex(2,3)); vc.push_back(complex(1,5)); vc.push_back(complex(-2,4)); sum_vc = accumulate(vc.begin(), vc.end(), complex(0,0), squared_sum () ); // computes the sum of squares of a vector of complex numbers

Standard C++ Exceptions (1)

Standard C++ Exceptions (2)

Standard C++ Exceptions (3)

Standard C++ Exceptions (4)