Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
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.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Starting Out with C++, 3 rd Edition 1 Chapter 16 – Exceptions, Templates, and the Standard Template Library (STL) Exceptions are used to signal errors.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
STL. What is STL? Standard Templates Library Templates are best used for –Defining containers for storing data –Some kinds of algorithms that work the.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
More on the STL vector list stack queue priority_queue.
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)
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: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair )
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’
Templates & Generic Programming Junaed Sattar November 12, 2008 Lecture 10.
Standard Template Library Programming paradigm: generic programming the decomposition of programs into components which may be developed separately and.
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.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Containers Overview and Class Vector
11 COS220 Concepts of PLs AUBG, COS dept Lecture 36 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++, Lafore, Chap 15 STL,
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
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.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
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,
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
Lecture 7 : Intro. to STL (Standard Template Library)
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
1 The Standard Template Library Drozdek Section 3.7.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Lecture 7-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Copyright © Curt Hill STL Priority Queue A Heap-Like Adaptor Class.
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
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
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
Lecture 36 OOP The STL Standard Template Library
Regarding homework 9 Many low grades
The C++ Algorithm Libraries
Collections Intro What is the STL? Templates, collections, & iterators
ADT Implementations: Templates and Standard Containers
C++ Functions, Classes, and Templates
priority_queue<T>
Elements are always copied when they are put into a container
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
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:

Templates & STL Instructor: 小黑

Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template can be used to generate many classes. template class temp_class { Name x,y; public: temp_class(); void fun1(); }; class temp_class { int x,y; public: temp_class(); void fun1(); }; class temp_class { char x,y; public: temp_class(); void fun1(); }; … temp_class a; temp_class b; …

Templates Two types of templates:  Function Template  Class Template Define Templates: template

Template’s Example void main() { X x1; //T1=int, T2=float X x2; //T1=char, T2= double* int i=3; fun( i); //T3=int } template class X ; //Class Template template void fun(T3 data) {} //Function Template //class and typename are the same

Partial Specialization template class X { public: X() { cout << “Construct”; } void display(T x) { cout << “Origin!”; } } ; template class X { public: X() { cout << “Construct”; } void display(int x) { cout << “Specialize!!”; } } ; X t1; X t2;

Function Specialization void X ::display(int x) { cout << “Integer!!”; } void X ::display(int x) { cout << “Character!!”; } template class X { public: X() { cout << “Construct”; } void display(T x) { cout << “Origin!”; } } ;

STL  Container classes  Sequences  vector, list  Associative Containers  map, set  Container adapters  Stack, queue, priority_queue  String String, rope  bitset  Operation/Utilities  iterator  algorithm

Vector #include using namespace std; int main () { vector v; // Template! for (int i=1; i<=10 ; i++) v.push_back(i); v.erase (v.begin()+5); v.erase (v.begin(),v.begin()+3); v.pop_back(); for (int i=0; i<v.size(); i++) cout << v[i] << " "; return 0; }  Dynamic array of variables, struct or objects.  Insert data at the end

Using iterator #include using namespace std; int main () { vector v1 (3,100); vector ::iterator it; it = v1.begin(); it = v1.insert (it,200); v1.insert (it,2,300); // "it" no longer valid it = v1.begin(); vector v2 (2,150); v1.insert( it+3, v2.begin(), v2.end()); int a1 [] = { 501,502,503 }; v1.insert (v1.begin(), a1, a1+3); for (it=v1.begin();it<v1.end(); it++) cout << *it << " "; cout << endl; return 0; }

Two and three dimensional vector #include using namespace std; int main () { vector > d2( 2,vector (3,0)); d2[0][0]=1, d2[0][1]=2, d2[0][2]=3; d2[1][0]=4, d2[1][1]=5, d2[1][2]=6; for (int i=0;i<(int)d2.size();i++){ for (int j=0; j<(int)d2[i].size();j++) cout << d2[i][j] << " "; cout << endl; } vector > > d3; d3.push_back(d2); cout << "Using iterator :" << endl; vector > >::iterator it1; vector >::iterator it2; vector ::iterator it3; for (it1=d3.begin();it1!=d3.end();it1++) for (it2=(*it1).begin(); it2!=(*it1).end();it2++) for (it3=(*it2).begin(); it3!=(*it2).end();it3++) cout << *it3 << " "; return 0; } Using iterator :

Map Maps are a kind of associative containers that stores elements formed by the combination of a key value and a mapped value. #include using namespace std; int main () { map mymap; mymap['a']="an element"; mymap['b']="another element"; mymap['c']=mymap['b']; cout << “'a' is " << mymap['a'] << endl; cout << “'b' is " << mymap['b'] << endl; cout << “'c' is " << mymap['c'] << endl; cout << “'d' is " << mymap['d'] << endl; cout << "mymap now contains " << (int)mymap.size() << " elements." << endl; return 0; } 'a' is an element 'b' is another element 'c' is another element 'd' is mymap now contains 4 elements.

Algorithm The header defines a collection of functions especially designed to be used on ranges of elements. We can accesses through iterators or pointers, such as an array or an instance of some of the STL containers.  for_each( iterator, iterator, *func)  find( iterator, iterator, T)  find_if( iterator, iterator, *func)  count( iterator, iterator, T)  find(…), find_if(…)  replace (…), replace_if(…)  sort(…)  binary_search(…)  search(…)

Sort example #include using namespace std; bool myfunction (int i,int j) { return (i<j); } struct myclass { bool operator() (int i,int j) { return (i>j); } } myobject; int main () { int myints[]={32,71,12,45,26,80,53,33}; vector v(myints, myints+8); vector ::iterator it; //using default comparison (operator <): sort (v.begin(), v.begin()+4); //( ) // using function as comp sort (v.begin()+4, v.end(), myfunction); // ( ) // using object as comp sort (v.begin(), v.end(), myobject); //( ) cout << "sort:"; for (it=v.begin(); it!=v.end(); it++) cout << " " << *it; cout << endl; return 0; } sort: template void sort ( Iter first, Iter last );

Search example #include using namespace std; bool myfunction (int i,int j) { return (i==j); } int main () { vector v; vector ::iterator it; for ( int i=0 ; i<10 ; i++ ) v.push_pack(i*10); // using default comparison: int match1[] = {40,50,60,70}; it = search (v1.begin(), v1.end(), match1, match1+4); if (it!=v.end()) cout << “match1 found at position " << int(it-v.begin()) << endl; else cout << "match not found" << endl; // using predicate comparison: int match2[] = {20,30,50}; it = search (v.begin(), v.end(), match2, match2+3, myfunction); if (it!=v.end()) cout << "match2 found at position " << int(it-v.begin()) << endl; else cout << "match2 not found" << endl; return 0; } match1 found at position 3 match2 not found

Today’s practice  Write a function called plus that uses function template. The function have two parameters and return the result of adding.  Use algorithm ” for_each” to output all data in the output vector. You can check the usage from the web page:

Today’s practice // YOUR CODE HERE int main() { int i = plus( 6, 2); double d = plus(1.67,8.2); cout << i << endl << d << endl; string s1= plus ("he", "llo"); string s2= plus ( s1, " again"); string s3= plus ( "b", "ye!"); vector output; output.push_back(s1); output.push_back(s2); output.push_back(s3); // YOUR CODE HERE // for_each(…) return 0; } You need to fill these vacancies.

Reference     