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,

Slides:



Advertisements
Similar presentations
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Advertisements

Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
More on the STL vector list stack queue priority_queue.
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
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,
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.
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
LECTURE LECTURE 17 More on the Standard Template Library 23 A guided tour with common examples of the containers.
Containers Overview and Class 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.
Object Oriented Programming Elhanan Borenstein Lecture #11 copyrights © Elhanan Borenstein.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
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.
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.
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.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
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.
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.
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.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
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.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
The Standard Template Library Container Classes Version 1.0.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
Copyright © Curt Hill STL Priority Queue A Heap-Like Adaptor Class.
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
Standard Template Library
Standard Template Library (STL)
ENERGY 211 / CME 211 Lecture 19 November 3, 2008.
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Iterators and STL Containers
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

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, charArray, stringArray

template 格式 : template class classname { …. }; - e.g., class Array of any type

template class Array { public: T& operator[ ] (int); Array(int); ~Array( ); int get_size( ) const { return size; } private: T* a; int size; T dummy_val; };

template T& Array ::operator[ ](int i) { if (i = size) { cerr << “index “ << I << “out of bounds”; return dummy_val; } return a[i]; } template const T& Array ::operator[ ](int i) const { if (i = size) { cerr << “index “ << I << “out of bounds”; return dummy_val; } return a[i]; }

template Array ::Array(int s) { a = new T[size =s]; } …

template int main( ) { Array a(100); // an integer array Array b(200); // a char array Array c(300); // a float array a[10] = 30; b[15] = ‘s’; c[20] = 35.99; … }

template more than one class parameters - e.g. template class Sample { public: T2 m(T3 p) { … } private: T1 x; … };

template function-style parameters - e.g. template class Array { public: Array( ); T& operator[ ] (int); … private: T* a; int size; T dummy_val; }; template Array ::Array( ) { a = new T[size = s]; }

template void main( ) { Array a1; Array a2; a1[5] = 20.9; a2[30] = ‘c’; … }

template Example: A template Stack class - p. 353 int main( ) { Stack s1; Stack s2; … }

template function templates (top-level functions) - e.g. template T min(const T &a, const T &b) { if (a < b) return a; else return b; }

function template (cont.) int main ( ) { int i=10; j=20; cout << min(i, j) <<endl; // integer function float f1=30.8; f2=40.4; cout << min(f1, f2) << endl; // float function … }

function template (example) template void Insertionsort(T a[ ], int n) { for (int i=1; i<n; i++) { if (a[ i ] < a[i-1]) { T v=a[ i ]; int j = i; do { a[ j ] = a[j-1]; --j; } while ((j>0) && (v <a[j-1])); a[ j ] = v; }

function template (cont.) int A[100]; float B[1000]; … Insertionsort(A, 100); Insertionsort(B,1000); …

Standard Template Library(STL) STL - a part of the standard C++ library - provide C++ with data structures Three elements in STL - Containers - template classes - Algorithms - functions that process the contents of containers - Iterators - “Pointers” for accessing the container’s objects

standard template library example: #include using namespace std; int main( ) { vector v; // container deque d; // container … sort(v.begin( ), v.end( )); // algorithm and iterators sort(d.begin( ), d.end( )); … }

standard template library basic containers - sequential - list, vector, deque - associative - set, multiset, map, multimap

standard template library Member functions for all containers - Default constructor, copy constructor, destructor - empty - max_size, size - = >= == != - swap Functions for first-class containers - begin, end - rbegin, rend - erase, clear, insert

standard template library vector - an array that grows and shrinks as needed - e.g. vector d; // no need to specify size vector a(100); // initialize 100 elements to 0, still grow // dynamically - more examples……

STL -- vector #include using namespace std; int main( ) { int i; vector nums; nums.insert(nums.begin( ), -999); nums.insert(nums.begin( ), 14); nums.insert(nums.end( ), 57); for (i = 0; i < num.size( ); i++) cout << nums[ i ] << endl;

STL -- vector cout << endl; nums.erase(nums.begin( )); for (i = 0; i < nums.size( ), i++) cout << nums[ i ] << endl; return 0; } nums nums.begin( ) nums.end( )

standard template library iterators - a mechanism for accessing the objects in a container one at a time - similar to “pointer’ but no need to handle address - const_iterator is used if the iteration does not change any of container’s elements - i.e. iterator for read/write const_iterator for read only

STL -- list #include using namespace std; void dump( list & ); int main( ) { list names; names.insert(names.begin( ), “Kamiko”); names.insert(names.end( ), “Andre”); names.insert(names.begin( ), “Chengwen”); names.insert(names.begin( ), “Maria”); dump(names);

STL -- list (cont.) names.reverse( ); cout << endl; dump(names); return 0; } void dump( list & l) { list ::const_iterator it; it = l.begin( ); while (it != l.end( )) { cout << *it << endl; it++; } Maria Chengwen Kamiko Andre Kamiko Chengwen Maria

standard template library iterators - e.g. list names; vector dv; deque my_q; list ::iterator it; list ::const_iterator cit; vector ::iterator vit; deque ::const_iterator cdit;

iterators it = names.begin( ); cout << *it << endl; it++; vit = dv.begin( ); while (vit != dv.end( )) { … } … operations of iterators - ++p, p++, *p, p=p1, p==p1, p!=p1, --p, p--, p+i, p-i, p[i], p+=i, p-=i (p, p1: iterators, i: integer)

standard template library four types of iterators - iterator forward read/write - const_iterator forward read - reverse_iterator backward read/write - const_reverse_iterator backward read

standard template library efficiency of vectors, deques, and lists Operation vector deque list insert/erase at beginning linear constant constant insert/erase at end constant constant constant insert/erase in middle linear linear constant access first element constant constant constant access last element constant constant constant access middle element constant constant linear

standard template library vector - good for insertion(deletion) at the end - less efficient to insert at the beginning deque - equally efficient for insertion(deletion) at both ends - both vector and dequeue overload [ ] operator (not for list)

basic associative containers set - a collection of zero or more nonduplicate unordered elements called keys - e.g. { 10, 20, 300, 25 } set of integers multiset - allow duplicate keys

basic associative containers map - a collection of zero or more unordered pairs; in each pair, one element is a nonduplicate key and the other is a value associated with the key - e.g {(1, “Jan”), (2, “Feb”), (3, “Mar”)} multimap - allow duplicate keys

set -- example #include using namespace std; int main( ) { set s; s.insert(-999); s.insert(18) s.insert(321); s.insert(-999); // duplicate – not inserted set ::const_iterator it; it = s.begin( ); while ( it != s.end( )) cout << *it++ << endl;

set -- example (cont.) int key; cout << “Enter an integer:”; cin >> key; it = s.find(key); if ( it == s.end( )) cout << key << “is not in set.” << endl; else cout << key << “is in set.” << endl; return 0; } Enter an integer: is not in set.

map -- example #include using namespace std; int main( ) { map m; m[“zero”] = 0; m[“one”] = 1; m[“two”] = 2; m[“three”] = 3; m[“foru”] = 4; m[“five”] = 5; m[“six”] = 6; m[“seven”] = 7; m[“eight”] =8; m[“nine”]; 9;

map – example (cont.) cout << m[“three”] << endl // 3 << m[“five”] << endl // 5 << m[“seven”] << endl; // 7 return 0; }

standard template library container adaptor - adapts a container to behave in a particular way - e.g. by default, STL stack adapts a deque - three container adaptors: stack, queue, priority queue

container adaptor stack - a LIFO (Last In First Out) data structure - by default, adapt deque queue - a FIFO (First In First Out) data structure - by default, adapt deque priority queue - a queue whose elements are removed in some priority order - by default, adapt vector

priority queue -- example #include #include // for rand and srand #include // for time using namespace std; int main( ) { const int howMany=8; int i; priority_queue nums; srand(time(0)); // seed rand

priority queue – example (cont.) for (i = 0; i < howMany; i++) { int next = rand( ); cout << next << endl; nums.push(next); } cout << “\n*** Priority by value:” << endl; for ( i = 0; i < howMany; i++) { cout << nums.top( ) << endl; nums.pop( ); } return 0; } *** Priority by value:

standard template library other containers - string, bitset algorithms - implemented as template functions, including - sorting - searching - numerical processing - set operations - copying - ref. p. 533

STL algorithms #include using namespace std; void printChar(char c) { cout << c; } int main ( ) { string s=“pele, the greatest ever”; cout << “s: “ << s << endl; cout << “s in reverse: “; for_each(s.rbegin( ), s.rend( ), printChar); cout << endl;

STL algorithms (cont.) char* where = find(s.begin( ), s.end( ), ‘a’); cout << “ ‘a’ is the “ << where – s.begin( ) + 1 << “th char in: << s << endl; random_shuffle(s.begin( ), s.end( )); cout << “s after a random shuffle: “ << s << endl; where = find(s.begin( ), s.end( ), ‘a’); cout << “ ‘a’ is the “ << where – s.begin( ) + 1 << “th char in: << s << endl; sort(s.being( ), s.end( )); cout << “ s sorted in ascending order: “ << s << endl; return 0; }

STL algorithms #include using namespace std; void dump (int i) { cout << i << endl;} bool odd(int i) { return i%2 != 0;} bool comp(const int& i1, const int& i2) { return i1 > i2;} int main( ) { vector v(10); generate(v.begin( ), v.end( ), rand); replace_if(v.begin( ), v.end( ), odd, 0);

STL algorithms (cont.) sort(v.begin( ), v.end( ), comp); for_each(v.begin( ), v.end( ), dump); return 0; }