Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.

Slides:



Advertisements
Similar presentations
Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
C++ fundamentals.
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.
Templates and the STL.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
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.
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
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 Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
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)
Array Size Macro approach 19 Macros Macros do not perform error checking. // macro approach #define macro_array_size(array) (sizeof(array)/sizeof(array[0]))
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
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,
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
Chapter 22 STL Containers §22.1 STL Basics §22.2 STL Iterators §22.3 Sequence Containers §22.4 Associative Containers §22.5 Container Adapters.
 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.
Lecture 7 : Intro. to STL (Standard Template Library)
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
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.
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)
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.
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.
Washington WASHINGTON UNIVERSITY IN ST LOUIS More on the STL: Function Objects and Generic Algorithms in the STL Fred Kuhns Computer Science and Engineering.
Object-Oriented Programming (OOP) Lecture No. 41
Motivation for Generic Programming in C++
Standard Template Library (STL)
STACKS AND QUEUES UNIT 2 DS THROUGH C++.
ENERGY 211 / CME 211 Lecture 19 November 3, 2008.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Containers and the Standard Template Library (STL)
Class string and String Stream Processing
Standard Template Library
Standard Template Library
An Introduction to STL.
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică

2Programming IIObject-Oriented Programming Course #9 Agenda C++ Standard Template Library (STL) Introduction Containers Algorithms and function objects Iterators and allocators Strings Streams Numerics

3Programming IIObject-Oriented Programming Library Organization In computer science, a library is a collection of subroutines or classes used to develop software. Libraries contain code and data that provide services to independent programs.computer sciencesubroutinesclassessoftware The main criterion for including a class in the library was that it would somehow be used by almost every C++ programmer (both novices and experts), that it could be provided in a general form that did not add significant overhead compared to a simpler version of the same facility, and that simple uses should be easy to learn. Essentially, the C++ standard library provides the most common fundamental data structures together with the fundamental algorithms used on them. Organization of the library: Containers Algorithms and Function Objects Iterators and Allocators Strings Streams Numerics

4Programming IIObject-Oriented Programming What’s provided by the C++ standard library? The C++ standard library: provides support for language features (memory management, RTTI) supplies info about implementation-dependent aspects (largest float value etc) supplies functions that cannot be implemented optimally in the language itself for every system (sqrt, memmove etc.) provides strings and I/O streams (with internationalization and localization support) provides a framework of containers (vectors, maps etc.) and generic algorithms (traversals, sorting, merging etc.) supports numerical computations (complex numbers, BLAS=Basic Linear Algebra Subprograms etc.) provides a framework for extending the provided facilities provides a common foundation for other libraries Framework of containers, algorithms and iterators is commonly referred as STL = Standard Template Library [Stepanov, 1994]

5Programming IIObject-Oriented Programming Containers (I) DEFINITON [Container] A container is an object that holds other objects. Examples: list, vectors, stacks etc. Using abstract classes to provide a standard interface for containers and iterators – it doesn’t meet the efficiency requirements! (small functions, that cannot be inlined because they are virtual). Advantages of containers: simple and efficient each container provides a set of common operations; they can be used interchangeably wherever reasonable standard iterators are available for each container type-safe and homogeneous are non-intrusive (i.e. an object doesn’t need to have a special base class to be a member of the container) each container takes an argument called allocator, which can be used as a handle for implementing services for every container (persistence, I/O)

6Programming IIObject-Oriented Programming Containers (II) vector citites; void addPoints(Point sentinel) { Point point; while(cin>>point) { if(point==sentinel) return; cities.push_back(point); // add the point to the end of the vector } Example: Basic containers: vector, list, deque. Other containers: stack, queue, priority queue (implemented using basic containers). Associative containers: map, multimap Almost containers: bitset, String, valarray

7Programming IIObject-Oriented Programming Allocators DEFINITION [Allocator] The allocator is an abstraction that insulates the container implementation from memory access/management details. Key concepts of an allocator: provides standard ways to allocate/deallocate memory provides standard names of types used as pointers or references Use allocators to offer garbage-collected memory management Standard allocator is implemented in class class allocator { } (included in ) and it uses operator new to allocate memory User-defined allocators usually override allocate and deallocate member functions. template class my_alloc { … } ; vector v; vector v2 = v; // ERROR: different allocators

8Programming IIObject-Oriented Programming Iterators DEFINITION [Iterator] Iterators are abstractions that provide an abstract view of data so that the writer of an algorithm doesn’t have to know the representation details of the data structure. DEFINITION [Sequence] A sequence is a collection of elements that can be traversed from the “beginning” to the “end” by using “next-element” operation. Key concepts of iterator: the element the iterator is pointing to: operator * or -> the next element in sequence: operator ++ equality: operator == Examples: int* is an iterator for int[], list ::iterator is an iterator for list Declared in std ; include const or modifiable Operations: read, write, access, iteration, comparison Iterator types: input, output, forward, bidirectional, random access Doesn’t check the range of the container

9Programming IIObject-Oriented Programming Vector (I) template > class std::vector { // types typedef T value_type; typedef … iterator; // T* // iterators iterator begin(); reverse_iterator rbegin(); // element access reference operator[] (size_type n); // constructors explicit vector(size_type n, const T& val=T(), const A&=A()); // operations void push_back(const T& x); // size and capacity void resize(size_type sz, T val=T()); }; template bool std::operator==( const vector & v1, const vector & v2); Declaration Allocator – supplies functions that a container uses to allocate/deallocate memory for its elements Iterator – pointers to elements of a container used to navigate the container Element access – operator [], at (checked access), front, back Constructors – constructors, copy- constructors, destructor Operations – push back, pop back, insert, erase, clear, push front, pop front, operator = Size and capacity – size, empty, resize,capacity, reserve Others – swap two vectors, get_allocator Helper functions – operator == and < There is a specialization for vector.

10Programming IIObject-Oriented Programming Vector (II) #include template typename C::value_type sum(const C& container) { typename C::value_type s = 0; typename C::const_iterator p = container.begin(); while(p!=container.end()) { s += *p; p++; } return s; }; void main() { vector v(32); for(int i=0; i<32; i++) v.push_back(i); int x = sum(v); cout << “Element 3-th” << v[3] << “ of total “ << v.size(); v.clear(); }

11Programming IIObject-Oriented Programming Iterators: special types Reverse iterator - A reverse iterator provides functions to iterate through elements in reverse order, from “end” to “beginning”. Implemented in reverse_iterator class; Containers provide rbegin and rend member functions to create reverse iterators. void f() { ostream_iterator os(cout); *os = 7; // output 7, cout << 7 ++os; // get ready for next output *os = 70; // output 70, cout << 70 } Checked iterators - provide range-checked access to sequence’s elements Checked_iter – the interface for they Stream iterators – present I/O streams as collections Available stream iterators: ostream_iterator, istream_iterator, ostreambuf_iterator, istreambuf_iterator. See example below:

12Programming IIObject-Oriented Programming Algorithms There are 60 algorithms in standard library; defined in std namespace; include Can be applied to standard containers, strings and built-in arrays Expressed as template function Standard Algorithms (a selection): Example: void f(list & ls) { list ::const_iterator p = find(ls.begin(), ls.end(), “Timisoara”); if(p==ls.end()) cout << “Didn’t find Timisoara”; } Classification: non modifying sequence modifying sequence sorted sequence others: set, heap, minimum, maximum, permutations

13Programming IIObject-Oriented Programming Function objects (I) Mechanism to customize standard algorithms behaviour In std namespace; include Example: template class SumMe { public: SumMe(T i=0) : sum(i) {} void operator() (T x) { sum+= x; } T result() const { return sum; } private: T sum; }; void f(vector v) { SumMe s; for_each(v.begin(), v.end(), s); cout << “Sum is “ << s.result(); } DEFINITION [Function object] An object of a class with an application operator overloaded is called function-like object / functor / function object. Advantages: support better complex operations than ordinary functions easier to inline

14Programming IIObject-Oriented Programming Function objects (II) Function object base – unary_function and binary_function Predicate – is a function object that returns a bool value; Ex: bool operator() (……); Examples of predicates supplied in standard library: equal_to, greater, less etc. Arithmetic function objects: plus, minus, etc. Binders, adapters and negaters Example: class Club { public: string name; // other members }; class Club_eq : public unary_function { string s; Public: explicit Club_eq(const string& ss) : s(ss) {} bool operator() (const Club& c) const { return s==c.name; } }; void f(list lc) { list ::iterator p = find_if(lc.begin(), lc.end(), Club_eq(“Poli”)); // if p==lc.end() -> club Poli not found // if p!=lc.end() -> club Poli found }

15Programming IIObject-Oriented Programming Strings DEFINITON [String] A string is a sequence of characters. Offered by class std::string in the header. Support common string operations such as: concatenation, insertion, subscripting, assignment, comparison, appending, searching for substrings, extract substrings. Supports any character set (using char_traits template) C-style character and string handling remains the same. Example: string f() { string s1 = “First string”; string s2 = s1, s3(s1, 6, 3); wstring ws(s1.begin(), s1.end()); // string of wchar_t s3 = s2; s3[0] = ‘A’; const char* p = s3.data(); // conversion to C-style string delete p; // ERROR: the array is owned by string object if(s1==s2) cout << “Strings have same content”; s1 += “ and some more…”; s2.insert(5, “smth”); string::size_type i1 = s1.find(“string”); // i1=6 string::size_type i2 = s1.find_first_of(“string”); // i2=3 s1.replace(s1.find(“string”), 3, “STR”); cout << s.substr(0, 5); cin >> s3; return s1 + ‘ ‘ + s2; // concatenation }

16Programming IIObject-Oriented Programming Streams #include // make standard strings available #include // make standard I/O available int main() { using namespace std ; string name; cout << “Enter your name:"; // prompt the user cin >> name; // read a name cout << "Hello, " << name << ´\ n´; cout.setf(ios_base::hex, ios_base::basefield); The challenge is to design an easy, convenient, safe to use, efficient, flexible I/O system able to handle user-defined types (on top of handling built-in types). The stream I/O facilities is the result of the effort of meet this challenge. standard input/output streams: cin, cout, cerr. overloaded operators: > support a variety of formatting and buffering facilities support any character set (ostream, wostream) cout << 123; // outputed in hex format cout.width(4); cout << 12; // “ 12” (preceded by two blanks) ofstream ofs; ofs.seekp(10); ofs<<‘#’; ofs.seekp(-1, ios_base::cur); ofs << ‘*’; return 0; }

17Programming IIObject-Oriented Programming Numerics (I) template class complex { public: complex(scalar re, scalar im); // …. } complex numbers: supports a family of complex numbers, using different scalar to represent real/imaginary part. void f(complex fl, complex db) { complex ld = fl+sqrt(db); db += fl*3; fl = pow(1/fl, 2); } Arithmetic operations and common mathematical functions are supported Examples:

18Programming IIObject-Oriented Programming Numerics (II) template class valarray { public: T& operator[](size_t); // size_t = unsigned int // …. } vector arithmetic is provided in valarray class different from vector class because they have different aims (vector – general, flexible, efficient mechanism for holding values; valarry – added math operations, less general and optimized for numerical computation) void f(const valarray & a1, const valarray & a2) { valarray a=a1*3 + a2/a1, aa; a += a2*6.7; aa = abs(a1); double d = a2[6]; } Example: supports BLAS-style and generalized slicing. Matrix can be constructed from valarray.

19Programming IIObject-Oriented Programming Further Reading [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 16, 17, 18, 19, 20, 21, 22][Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 16, 17, 18, 19, 20, 21, 22] [Stepanov, 1994] Alexander Stepanov and Meng Lee - The Standard Template Library. HP Labs Technical Report HPL (R. 1). August, [Stroustrup, 1999] Bjarne Stroustrup - An Overview of the C++ Programming Language in “The Handbook of Object Technology” (Editor: Saba Zamir). CRC Press LLC, Boca Raton ISBN