The Standard Template Library. Books on standard C++ library Nicolai M. Josuttis: C++ Standard Library: A tutorial and Reference, 1st, Pearson 1999, Nicolai.

Slides:



Advertisements
Similar presentations
Hold data and provide access to it. Random-access containers: -Allow accessing any element by index -arrays, vectors Sequential containers: -Allow accessing.
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Data Structures Using C++ 2E
Multimaps. Resources -- web For each new class, browse its methods These sites are richly linked, and contain indexes, examples, documents and other resources.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Introduction to the STL
The Standard Template Library – part 2. auto_ptr Regular pointers may cause memory leaks Regular pointers may cause memory leaks void f() { SomeClass.
Week 5 - Associative Containers: sets and maps. 2 2 Main Index Main Index Content s Content s Container Types Sequence Containers Adapter Containers Associative.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++
Generic programming starts with algorithms. Lift Minimal requirements: works with maximal family of types Concrete algorithm: requires specific data type.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
Templates and the STL.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
Writing Your Own STL Container Ray Lischner
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Standard Template Library Programming paradigm: generic programming the decomposition of programs into components which may be developed separately and.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
1 Today’s Objectives  Announcements The Final Exam will be on Monday, 31-Jul, at 6 p.m. – There is no alternate time and no makeup!  Intro to the Standard.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Introduction to C & C++ Lecture 6 – STL JJCAO.
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)
The C++ Standard Template Library. What is STL A subset of the standard C++ library –The string class is not part of it! 3 major components –Algorithms.
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
C++ STL CSCI 3110.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
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.
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.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
 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.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
The Standard Template Library Container Classes Version 1.0.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
CSCI-383 Object-Oriented Programming & Design Lecture 30.
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.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Object-Oriented Programming (OOP) Lecture No. 41
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
The Standard Template Library
Standard Template Library
Standard Template Library
Standard Template Library
Presentation transcript:

The Standard Template Library

Books on standard C++ library Nicolai M. Josuttis: C++ Standard Library: A tutorial and Reference, 1st, Pearson 1999, Nicolai M. Josuttis: C++ Standard Library: A tutorial and Reference, 1st, Pearson 1999, examples: (Polish: Nicolai M. Josuttis: C++ Biblioteka standardowa Podręcznik Programisty, Helion 2003, examples: ftp://ftp.helion.pl/przyklady/cpbspp.zip) (Polish: Nicolai M. Josuttis: C++ Biblioteka standardowa Podręcznik Programisty, Helion 2003, examples: ftp://ftp.helion.pl/przyklady/cpbspp.zip) (Grębosz J.: Pasja C++, RM, W-wa) (Grębosz J.: Pasja C++, RM, W-wa) Other (mentioned on Lecture Nr 1) Other (mentioned on Lecture Nr 1)

Standard library of C++ language STL STL (The main part of standard library of C++ language) Stream classes Stream classes String classes String classes (library defined within std namespace)

Standard Template Library Main elements Main elements Generic data containers (lists, vectors, etc.) Generic data containers (lists, vectors, etc.) Iterators for browsing containers and providing an interface to containers for algorithms Iterators for browsing containers and providing an interface to containers for algorithms Algorithms operating on containers Algorithms operating on containers Other (to be discussed later...) Other (to be discussed later...) It is a template library! It is a template library! Data is generally separated from methods (where the OOP idea has gone?) Data is generally separated from methods (where the OOP idea has gone?) Designed for high-level programming Designed for high-level programming Designed for efficient programming Designed for efficient programming

BTW: algorithm’s complexity order O-notation O-notation find element in sorted array:O(log 2 (n)) find element in sorted array:O(log 2 (n)) find element in unsorted array: O(n) find element in unsorted array: O(n) quicksort:O(n · log 2 (n)) quicksort:O(n · log 2 (n)) bubblesort:O(n 2 ) bubblesort:O(n 2 )

Containers Sequential Sequential vector (dynamic table) vector (dynamic table) dequeue (double ende queue, using dynamic table) dequeue (double ende queue, using dynamic table) list (double linked one) list (double linked one) (arrays and strings not STL containers, but operable by STL algorithms) (arrays and strings not STL containers, but operable by STL algorithms) Associative Associative set (using binary tree) set (using binary tree) multiset multiset map, multimap map, multimap

Containers vector vector implemented as a dynamic table implemented as a dynamic table fast push_back() fast push_back() fast operator[] fast operator[] slow insert() slow insert()

Containers deque deque implemented using dynamic table implemented using dynamic table fast push_back() (here vector may be faster) fast push_back() (here vector may be faster) fast push_front() (not in vector template) fast push_front() (not in vector template) fast operator[] fast operator[] slow insert() slow insert()

Containers list list implemented using double linked list implemented using double linked list fast push_back() fast push_back() fast push_front() fast push_front() fast insert() fast insert() no operator[] no operator[]

Iterators Iterators behave like regular pointers... Iterators behave like regular pointers... * -> * -> ==!= ==!= = (vector, deq: -,, +(int) ) (vector, deq: -,, +(int) ) But work for all the containers! But work for all the containers! container.begin()// return iterator of first elem. container.begin()// return iterator of first elem. container.end()// return iterator next to last elem. container.end()// return iterator next to last elem. example: list2.cpp example: list2.cpp

Containers set set implemented using binary tree implemented using binary tree sorted at insert (by default using operator<() ) sorted at insert (by default using operator<() ) equivalent to math. sets equivalent to math. sets find() method find() method fast insert() fast insert() no push_back() no push_back() no push_front() no push_front() no operator[] no operator[]

Containers multiset multiset set that allows repetitions of the same value set that allows repetitions of the same value ordering within group of elements of the same value is undefined ordering within group of elements of the same value is undefined

Containers multimap multimap multiset of pairs: key, val – use make_pair() multiset of pairs: key, val – use make_pair()

Containers map map set of pairs: key, val – use make_pair() set of pairs: key, val – use make_pair() For map only: operator[key]() For map only: operator[key]() index by value (associative array) index by value (associative array)

STL Algorithms Operate on containers using iterator interface Operate on containers using iterator interface generic, but not as fast as containers’ methods generic, but not as fast as containers’ methods slow on some combinations of algorithm/container slow on some combinations of algorithm/container may operate on various containers at the same time may operate on various containers at the same time Only elementary, simple algorithms Only elementary, simple algorithms parametrizable by different iterators parametrizable by different iterators parametrizable by function objects and adaptors parametrizable by function objects and adaptors Not very intuitive (an euphemism) Not very intuitive (an euphemism)

STL Algorithms Example: algo1.cpp Example: algo1.cpp min_element// operator<() min_element// operator<() max_element// operator<() max_element// operator<() sort// operator<() sort// operator<() find// operator==() find// operator==() reverse// operator=() reverse// operator=() min_element (coll.begin(), coll.end()) min_element (coll.begin(), coll.end()) range is [ coll.begin(), coll.end() ) (example: find1.cpp) range is [ coll.begin(), coll.end() ) (example: find1.cpp) proper range definition is a programmer’s responsibility proper range definition is a programmer’s responsibility range end should be attainable by ++’ing of start range end should be attainable by ++’ing of start what if we’re not sure of what is beginning, what is end? what if we’re not sure of what is beginning, what is end?

STL Algorithms copy (coll1.begin(), coll1.end(), coll2.begin()); copy (coll1.begin(), coll1.end(), coll2.begin()); end of range given only for first range end of range given only for first range sizes of ranges must suffice sizes of ranges must suffice algorithm does elementary copy only algorithm does elementary copy only doesn’t check destination size (iteartors are intreface to elements, not to whole collection) doesn’t check destination size (iteartors are intreface to elements, not to whole collection) proper collection size is a programmer’s responsibility (example: copy2.cpp) proper collection size is a programmer’s responsibility (example: copy2.cpp) setting initial collection size is easy for some (sequential) container classes setting initial collection size is easy for some (sequential) container classes

STL Iterators sizes of ranges must suffice, or... sizes of ranges must suffice, or... copy (coll1.begin(), coll1.end(), inserter(coll2, coll2.begin()) );... or use inserter iterators ;) (example: copy3.cpp)... or use inserter iterators ;) (example: copy3.cpp) inserter for all containers, all can insert() inserter for all containers, all can insert() inserts before specified location inserts before specified location for associative containers location is a hint only for associative containers location is a hint only back_inserter for containers that can push_back() back_inserter for containers that can push_back() front_inserter for containers that can push_front() front_inserter for containers that can push_front()

STL Iterators stream iterators stream iterators behave like regular ones behave like regular ones have interface of regular ones have interface of regular ones operate on i/o streams (example: ioiter1.cpp) operate on i/o streams (example: ioiter1.cpp) istream_iterator (cin) istream_iterator (cin) ++iter for stream>>temp, *iter for retrieving temp ++iter for stream>>temp, *iter for retrieving temp istream_iterator () istream_iterator () end of stream iterator end of stream iterator

STL Iterators reverse iterators reverse iterators have interface of regular ones have interface of regular ones reverse regular behaviour (example: rter1.cpp) reverse regular behaviour (example: rter1.cpp) container.rbegin() is actually last element (not the one after last) container.rbegin() is actually last element (not the one after last) container.rend() is actually element before first one! container.rend() is actually element before first one! ++ is --, -- is ++, etc. ++ is --, -- is ++, etc.

STL Algorithms removing elements from container removing elements from container remove(...) algorithm remove(...) algorithm actually doesn’t remove container contents (example: remove1.cpp) actually doesn’t remove container contents (example: remove1.cpp) elementary operation of moving elements elementary operation of moving elements doesn’t know the container, knows elements doesn’t know the container, knows elements doesn’t work for associative containers doesn’t work for associative containers returns new end of range (next to last) returns new end of range (next to last) use method erase(...) to get rid of elements (example: remove2.cpp) use method erase(...) to get rid of elements (example: remove2.cpp) many versions many versions works for associative containers (example: remove3.cpp) works for associative containers (example: remove3.cpp)

Extending STL programmer is allowed (and encouraged) to extend STL functionality programmer is allowed (and encouraged) to extend STL functionality create new templates, or just classes/functions create new templates, or just classes/functions example: print.hpp example: print.hpp typename keyword denotes argument’s type/class typename keyword denotes argument’s type/class as opposed to „mutable” it is usefull as opposed to „mutable” it is usefull

Function as algorithm argument single argument functions single argument functions examples: foreach1.cpp, transform1.cpp examples: foreach1.cpp, transform1.cpp predicates predicates single argument and bool result (example: prime1.cpp) single argument and bool result (example: prime1.cpp) two arguments and bool result (example: sort1.cpp) two arguments and bool result (example: sort1.cpp)

Function object as algorithm argument function objects function objects behave like functions, but using operator()() behave like functions, but using operator()() example: foreach2.cpp example: foreach2.cpp are objects are objects easily optimizable by compiler easily optimizable by compiler may have class member variables, „internal state” passed by the constructor argument (example: add1.cpp) may have class member variables, „internal state” passed by the constructor argument (example: add1.cpp) we may have many function objects of the same class we may have many function objects of the same class

Function object as algorithm argument predefined function object templates predefined function object templates less<>, greater <> less<>, greater <> set s; defaults to set > s; we may also:set > s; we may also:set > s; negate<>, multiply<> // use in transform(...) algorithm negate<>, multiply<> // use in transform(...) algorithm

Function adaptors define special cases of function use define special cases of function use adapt function, when different interface (i.e. argument list) is required adapt function, when different interface (i.e. argument list) is required bind2nd(less (),50) (example: fo1.cpp) bind2nd(less (),50) (example: fo1.cpp) creates default second argument creates default second argument

Container elements interface required always interface required always copy constructor copy constructor assignment operator assignment operator destructor destructor interface required sometimes interface required sometimes default constructor default constructor equality operator == equality operator == comparison operator < comparison operator <

STL, errors and exceptions aimed at maximizing speed aimed at maximizing speed in case of improper use (*end()=something) behaviour is undefined, let’s hope it crashes in case of improper use (*end()=something) behaviour is undefined, let’s hope it crashes be carefull with iterators and ranges be carefull with iterators and ranges only minimal chcecks are done (bad_alloc exception) only minimal chcecks are done (bad_alloc exception) there is a debug version of the library there is a debug version of the library use it! use it! some methods of some containers are transaction-safe some methods of some containers are transaction-safe some are not! some are not! check the reference! check the reference!