Array Size Macro approach 19 Macros Macros do not perform error checking. // macro approach #define macro_array_size(array) (sizeof(array)/sizeof(array[0]))

Slides:



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

Beginning C++ Through Game Programming, Second Edition
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.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
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)
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Templates and the STL.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
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 Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Data Structures Using C++ 2E
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 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.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
Generic Positional Containers and Double-Ended Queues.
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)
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
Pointers OVERVIEW.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
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.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
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.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
Lecture 7 : Intro. to STL (Standard Template Library)
A gentle introduction to the standard template library (STL) Some references:
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Introduction to Templates and Standard Template Library 1.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
1 Generic Positional Containers and Double-Ended Queues.
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.
CS212: Object Oriented Analysis and Design
Standard Template Library
Standard Template Library (STL)
Collections Intro What is the STL? Templates, collections, & iterators
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
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
The List Container and Iterators
Presentation transcript:

Array Size Macro approach 19 Macros Macros do not perform error checking. // macro approach #define macro_array_size(array) (sizeof(array)/sizeof(array[0])) int ja[] = {0,1,2,3,4,5,6}; s = macro_array_size(ja); cout << “array_size = " << s << endl; //correct, returns 7 // int* pa = ja; int* pa = &ja[0]; s = macro_array_size(pa); //fails, returns 1 cout << "macro_array_size = " << s << endl; //fails, returns 1

Array Size Function template approach 19 array_size() Here we pass an array by reference to array_size() that extracts the size of the array and returns it template template inline size_t array_size(const T (&lhs)[N]) { return N; return N;} int ja[] = {0,1,2,3,4,5,6}; s = array_size(ja); cout << "function template approach: " << s << endl; //correct, returns 7 // int* pa = ja; int* pa = &ja[0]; s = array_size(pa); // fails, no matching function for call // to `array_size(int*&) cout << "macro_array_size = " << s << endl; // fails, no matching function for call // to `array_size(int*&)

Array Size Class template approach 19 N Here, N must be defined during the template class declaration, however. template template class CalcArraySize{ public: CalcArraySize(const T (&lhs)[N]) : size(N) { } CalcArraySize(const T (&lhs)[N]) : size(N) { } size_t getSize() { return size; } size_t getSize() { return size; }protected: size_t size; size_t size;}; int ia[10]; CalcArraySize a(ia); s = a.getSize(); 10 will be a fixed limit and that’s not exactly what we want.

Array Size Two arguments are still required 19 This works, but with two arguments required. Vector(T* a, unsigned s) : size(s) { data = new T[size]; data = new T[size]; for(int i=0; i < size; i++) { for(int i=0; i < size; i++) { data[i] = a[i]; }} int a[] = {11, 22, 33, 44, 55, 66, 77}; Vector v(a, sizeof(a)/sizeof(a[0]));

LECTURE LECTURE 17 STL 21 Standard Template Library

6STL 19 Bjarne Stroustrup, The C++ Programming Language (3rd Ed.), A Tour of the Standard Library

7STL Some Terms What is STL? 19 STL STL is a set of general-purpose template classes, built using the template mechanism. What are its main parts? Containers Iterators Algorithms

8STLContainers 19 Containers Containers are objects that hold other objects. Sequence container: A container whose elements are kept in an ordinal sequence, like an array. The position of each element is independent of its value. vector (direct array access) deque (double-ended queue) list (linked-list, no indexed access, faster insertion/deletion) What are they? Different types of containers:

9STLContainers 19 Associative container: A container whose elements are kept in a sorted order for allowing efficient retrieval of values based on keys. The positions of the elements are completely determined by their values and those of the other elements in the container. map (look-up table structure) sets (represent mathematical sets using union and intersection operations)

10STL Preamble to Iterators 19 #include using namespace std; template // a generic function to print an array printArray void printArray( T* a, int len ){ for(int j=0; j < len; j++) { cout << a[j] << " "; } cout << endl; } Function Template

11STL Preamble to Iterators 19 int main(){ //typedef long int MyType; typedef long long int MyType; const int Length = 10; MyType array[Length]; cout << "Size of MyType is: " << sizeof(MyType ) << endl; for( int i=0;i<Length;i++) { array[i] = i + 1; } printArray( array, Length ); MyType This code will work regardless of what MyType actually is.

12 #include using namespace std; template // a generic func to print an array void printArray( T * a, int len ){ for(int j=0;j<len;j++) cout << a[j] << " "; cout << endl; } int main(){ //typedef long int MyType; typedef long long int MyType; const int Length = 10; array MyType array[Length]; cout << "Size of MyType is: " << sizeof(MyType ) << endl; for( int i=0;i<Length;i++){ array array[i] = i + 1; } array printArray( array, Length ); MyType *ptr; array MyType *start = array; array MyType *end = array + Length; for( ptr = start; ptr != end; ptr++){ *ptr * = -1; *ptr * = -1; cout << ptr << endl; cout << ptr << endl; } array, printArray( array, Length ); return 0; } Preamble to iterators: Pointer arithmetic Example Output: Size of MyType is: xbffffc10 0xbffffc18 0xbffffc20 0xbffffc28 0xbffffc30 0xbffffc38 0xbffffc40 0xbffffc48 0xbffffc50 0xbffffc This code will work regardless of what MyType actually is. operators +,The operators +, etc are all overloaded for pointers so that pointer arithmetic works as it should.

13 Vector class Vectors are dynamic arrays: arrays that can grow as needed. The template specification for the vector class is: template class vector{ //... }; When using the vector type the required header to be included is

14 Vector class Vectors, being objects have additional advantages over ordinary arrays: it can be assigned values quickly (overloaded assignment operator) it can be passed by value it can be returned by value

15 Vector class vector(); //default constructor, creates an empty vector vector(const vector* v); //copy constructor: creates a copy of the vector v; //postcondition: *this == v; vector(unsigned n, const T& x = T()); //constructor: creates a vector containing n copies of the element x; //precondition: n >= 0; //postcondition: size() == n; ~vector(); //destructor Some important methods:

16 Vector class vector& operator=(const vector& v); //assignment operator: assigns v to this vector, making a duplicate //postcondition: *this == v; unsigned size() const; //returns the number of elements in //this vector unsigned capacity() const; //returns the maximum number of elements that this vector can have without being reallocated void reserve(unsigned n); //reallocates this vector to a //capacity of n elements //precondition: capacity() <= n //postcondition: capacity() == n bool empty() const; // true iff size() == 0; Some important methods:

17 Vector class void assign(unsigned n, const T& x=T()); //clears this vector and then inserts n copies of the element x; //postcondition: n >= 0; //postcondition: size() == n; T& operator[](unsigned i); //returns element at index i //precondition: 0 <= i <= size(); //result is unpredictable if precondition is false; T& at(unsigned i); // returns element at index i //precondition: 0 <= i <= size(); //exception is thrown if precondition is false; Some important methods:

18 Vector class T& front(); //returns the first element of this vector T& back(); //returns the last element of this vector iterator begin(); //returns an iterator pointing to the first element of this vector iterator end(); //returns an iterator pointing to the dummy element that follows the last element of this vector void push_back(const T& x); // appends a copy of the element x to the back of this vector; //precondition: back() == x; //postcondition: size() has been incremented; Some important methods:

19 Vector class void push_back(const T& x); // appends a copy of the element x to the back of this vector; //precondition: back() == x; //postcondition: size() has been incremented; void pop_back(); // removes the last element of this vector; //precondition: size() > 0; //postcondition: size() has been decremented; Some important methods:

20 Vector class iterator insert(iterator p, const T& x); // inserts a copy of the element x at position p; returns p; //precondition: begin() <= p <= end(); //postcondition: size() has been incremented; Some important methods:

21 Vector class iterator erase(iterator p); // removes the element at position p; returns p; //precondition: begin() <= p <= end(); //postcondition: size() has been decremented; iterator erase(iterator p1, iterator p2); // removes the elements from position p1 to the position before p2; //returns p1 //precondition: begin() <= p1 <= p2 <= end(); //postcondition: size() has been decremented by int(p2-p1); void clear(); //removes all elements //postcondition: size() == 0; Some important methods:

22 Vector class Declaring/ defining a vector: vector iv; vector cv(5); vector cv(5, 'x'); vector iv2(iv);

23 Vector class Using a vector: // display original size of v v.size() cout << "Size = “ << v.size() <<endl; /* put values onto end of a vector; the vector will grow as needed */ for(i=0; i<10; ++i) v.push_back(i); // change contents of a vector for(i=0; i < v.size(); ++i) v[i] = v[i] + v[i];

24 Vector class // access using subscripting for(i=0; i<10; ++i) { v[i] cout << v[i] <<" "; } cout << endl; // access via iterator vector ::iterator p = v.begin(); while(p != v.end()) { *p cout << *p << " "; ++p; } Declaring an iterator: container_name :: iterator iterator_name

25 Iterator An Iterator is just a convenient pseudo-pointer that is set up as a type to use associated with each container class. Various operators will have been set up to use with them e.g. =, ==, != and += Standard idiomatic form: int array[10]; for(int i=0; i<10; i++){ } Becomes: vector v(10); vector ::iterator it; for(it=v.begin();it != v.end();it++){ }

26 Iterators Iterators objects Iterators are objects designed to give us the ability to cycle through the content of a container. They act like pointers, locating one item in the container at a time. All iterators have the same basic functionality, regardless of the type of container to which they are attached. The fundamental operations are: initialise the iterator at some initial position in the container return the data value stored at the current position change the data value stored at the current position determine whether there actually is an item at the iterator’s current position advance to the next position in the container

Iterators can be adapted to provide backward traversal. ForwIter template printForwIterForwIter void print(ForwIter first, ForwIter last, const char* title){ cout << title << endl; while ( first != last) cout << *first++ << '\t'; cout << endl; } Iterators

28 int main(){ int data[3] = { 9, 10, 11}; vector d(data, data + 3); //auxiliary constructor vector ::reverse_iterator p = d.rbegin(); print(p, d.rend(), "Reverse"); //... } Example that uses a reverse iterator to traverse a sequence. Iterators See vector_2009.cpp See vector_countries.cpp

29 Let’s have a look at the Matrix class template implemented by connecting to the STL vector via composition. Samples 2-D array using pure vector *> See vector_of_vectors.cpp See Matrix_stl.cpp

30 STL The standard template library (STL) is the C++ library that provides generic programming for many standard data structures and algorithms. Containers associative Containers come in two major families: sequence (are ordered) and associative (have keys for looking up elements). Iterators can be thought of as an enhanced pointer type. The algorithms use iterators to access containers.Summary

31 Other standard components STL relies upon several other standard components for support: allocators: to manage memory allocation for a container predicates: special functions returning true/false results comparison functions, etc.

32 C++ Standard C++Standard: International standard for the C++ programming language approved! Morristown, New Jersey, USA, Friday, November 14, 1997 FOR IMMEDIATE RELEASE This week, technical experts representing eight countries and about 40 companies involved with software technologies met in Morristown, New Jersey and completed the content of an international standard for the C++ programming language.

33 Scope of the Standard: The C++ standard covers both the C++ language itself and its standard library. The standard library provides standard input/output, strings, containers (such as vectors, lists, and strings), non-numerical algorithms (such as sort, search, and merge), and support for numeric computation.

34 The ISO/ANSI Standard for C++ was unanimously approved by the C++ Standardization Committee on June 23, From: The current status (June’99) is that C++ has an International Standard and the committee are in the process of handling Defect Reports. We shall continue to do this until 2003 when ISO rules require us to revise the Standard. From:

35 Iterators There are five iterator types: input output forward bidirectional random access

36 Container classes and algorithms dictate the category of iterator available or needed. vector containers allow random-access iterators lists do not; sort requires random-access iterators find requires an input iterator. Iterators