C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Data Structures Using C++ 2E
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Beginning C++ Through Game Programming, Second Edition
Introduction to the STL
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
More on the STL vector list stack queue priority_queue.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
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.
Object Oriented Data Structures
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
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.
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.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
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.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
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.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
C++ Review STL CONTAINERS.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
CS212: Object Oriented Analysis and Design Lecture 26: STL Containers.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
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.
CPSC 252 Templatization Page 1 Templatization In CPSC152, we saw a class vector in which we could specify the type of values that are stored: vector intData(
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.
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
Motivation for Generic Programming in C++
Regarding homework 9 Many low grades
Programming with ANSI C ++
C++ Templates.
Templates.
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Collections Intro What is the STL? Templates, collections, & iterators
ADT Implementations: Templates and Standard Containers
CS212: Object Oriented Analysis and Design
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
An Introduction to STL.
SPL – PS1 Introduction to C++.
Presentation transcript:

c++ Templates

What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used with any data type Typing is determined by the client Type enforcement is maintained for the type that is initiated by the client More than one type can be created for more than one object created from the same template class vector ivector; vector svector;

Template versus Typedef typedef int item; item maximal(item a, item b) { if (a > b) return a; else return b; }

Template versus Typedef template Item maximal(Item a, Item b) { if (a > b) return a; else return b; }

How To Make a Template Class: Class Definition Add template line before class definition in header file

Template versus Typedef class bag { public: typedef int value_type;... }

Template versus Typedef Template class bag { public: typedef int value_type;... }

How To Make a Template Class: Functions Use class name as usual within class definition in header file Outside of class definition, tack onto the name of your class. e.g. use bag instead of bag when referring to the bag class name. Use Item instead of other data type for objects of your class. Ask yourself is this really a string (or whatever) or is it really an Item? return values parameter lists

Examples return values Member function (ex. pp. 296) prototype (in class def): Item grab(); implementation (after class def): template Item bag ::grab() { code here} Non Member function prototype (after class def): bag operator +(parameter list here); implementation (after class def): template bag operator+(parameter list here) { code here}

Examples parameter lists Member function prototype (in class def) void insert(const Item& entry); implementation (after class def, bag needed) void bag ::insert(const Item& entry) { code here} Non Member function prototype (after class def) bag operator +(const bag & b1, const bag & b2); implementation (after class def, no bag needed) bag operator +(const bag & b1, const bag & b2); { code here}

How To Make a Template Class: Implementation Make the implementation visible Typing is determined by the client compilation is performed when class becomes an object No using namespace std in implementation std:: required instead for all std namespace references Separate.cpp implementation file is not allowed. either put the entire implementation in header after class definition or remove implementation from project and add the #include class.cpp line after the class definition in the header file

How To Make a Template Class: Client #include.h file using namespace std is okay in client Declare an object of your template class with the. bag letters; bag scores; bag verbs: //include string class

Templates are Type Safe #include void TestVector() { vector nums; nums.add(7); vector words; words.add(“apples”); nums.add(“banana”); //compile error char c = words.getAt(0); //compile error vector s = nums; //compile error }

typedef Rewind typedef is an alias to a data type that can be defined in a class Can be used to aid in maintenance (easy to change data type throughout class Can be used to make another name for data types like std::size_t typedef std::size_t size_type Can also be used to identify items in a bag (was that a regular int or a bag item int?) typedef int value_type Even in a templated bag typedef Item value_type

Typedef Considerations with Template Implementations Example from text pp. 296 Before template bag::size_type bag::count(const Item& target) const After template bag ::size_type bag ::count(const Item& target) const Doesn't work typename bag ::size_type bag ::count(const Item& target) const compiler has no idea that bag ::size_type is a data type. It needs a new keyword typename

The Standard Template Library is a library of generic container classes which are both efficient and functional Templated- can handle many types In namespace std Google for “C++ STL” for documentation C++ STL developed in early 90's at Hewlett Packard Laboratories Alex Stepanov and Meng Lee became part of C++ standard in 1994 implementations available by late 90's

STL STL is part of a movement toward libraries of reusable code function libraries (reusable algorithms) class libraries (reusable ADTs) STL separates data and algorithms

STL Components Containers  templates for classes which hold a collection of elements Algorithms  templates for functions which operate on a range of elements from a container  range is specified by iterators Iterators  give access to the elements in a container  allow for movement from one element to another

STL Container Classes Sequences - elements arranged in a linear order and accessed by relative or absolute position vector - dynamic array. fast inserts only at the end; random access list - linked list. fast inserts anywhere; no random access deque - doubly ended queue. Fast inserts at the beginning and the end. Associative Containers - elements are key values for access by content not position Associative containers organize their data using keys which allow elements stored in the container to be accessed randomly Examples: set- a collection of unique items multi-set- a collection of non-unique items map – a two dimensional array (table)

STL Algorithms are function templates designed to operate on a sequence of elements rather than methods the sequence is designated by two iterators most container classes have the following two methods begin( ) - returns an iterator positioned at the container's first element end( ) - returns an iterator positioned past the container's last element (past-the-end)  some examples of STL algorithms find (iter1, iter2, value) //returns an iterator max_element (iter1, iter2) //returns an iterator sort (iter1, iter2) //sorts for data type

STL Iterators The following iterator operations are supported for all of the library containers *iter - Returns a reference to the element referenced by iterator iter. iter++ - Increment iter (move to the next element). iter-- - Decrement iter (move to the previous element). iter1 == iter2 - Compare two iterators for equality or inequality. Two iterators are equal if they both reference the same element in the same container or if they are positioned "one past the end" of the container. An iterator positioned "one past the end" is sometimes called the off-the-end iterator

Iterator Example #include using namespace std; // This program demonstrates the use of an iterator int main() { cout << "Iterator example" << endl; vector vals; vector :: iterator p; for(int i = 0; i < 10; ++i) vals.push_back(i*2+1); // output using an iterator for(p = vals.begin( ); p < vals.end( ); ++p) cout << *p << endl; }

list class another STL container class used for storing a linear collection of like items comparison to a vector? linked list vs array is the underlying data structure no indexing (iterators are bidirectional) inserts and deletes anywhere are done in a constant amount of time

a list data structure

Basic list class methods list( ); // construct an empty list list (const list & aList); // copy constructor ~list( ); // destructor list operator= (const list & aList); // assignment operator bool empty( ); int size( );

More List Methods L.push_back(value) // append value to L L.push_front(value) // insert value at front of L L.insert(pos, value) // insert value into L at // position indicated by iterator pos L.front( ) // return L's first element L.back( ) // return L's last element L.begin( ) // return an iterator positioned at start L.end( ) // return the"past the end" iterator L.sort( ) // sort L's elements

#include using namespace std; int main ( ) { list L; L.push_back (9); L.push_back (7); L.push_back (5); L.push_back (3); list ::iterator p; for (p = L.begin ( ); p != L.end ( ); p++) cout << *p << endl; for (p = L.begin ( ); p != L.end ( ); p++) (*p)++; for (p = L.begin ( ); p != L.end ( ); p++) cout << *p << endl; return 0; }

Another List Example int i; list int_list; list ::iterator iter; for (i=1; i<=10; i++) int_list.push_back(i); for (iter = int_list.begin(); iter != int_list.end(); iter++) cout << *iter << “ “ ;

Iterators in Loops General pattern for (i = c.begin(); i != c.end(); i++) { statements to access item}

STL Set and Multiset #include <set data stored in sorted order set holds sorted unique values as keys multiset holds sorted non-unique values functions include insert erase swap clear size