Generic Algorithms (TIC++V2:C6)

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

Vectors, lists and queues
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
STL. What is STL? Standard Templates Library Templates are best used for –Defining containers for storing data –Some kinds of algorithms that work the.
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
1 Lecture 8: Introduction to C++ Templates and Exceptions  C++ Function Templates  C++ Class Templates.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
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.
CNS  Executive Overview  Template Parameters  Function Template Issues 2 CNS Templates.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
ITERATORS. Iterator An iterator in C++ is a concept that refines the iterator design pattern into a specific set of behaviors that work well with the.
Copyright 2006, The Ohio State University Introduction to C++ Templates l C++ Function Templates l C++ Class Templates.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
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.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Motivation for Generic Programming in C++
C++ Lesson 1.
Lecture 7-2 : STL Iterators
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
CSCE 210 Data Structures and Algorithms
Command Line Arguments
Programming fundamentals 2 Chapter 1:Array
Generic Programming Techniques in C++
Templates in C++.
The C++ Algorithm Libraries
Collections Intro What is the STL? Templates, collections, & iterators
Reserved Words.
Lecture 7-3 : STL Algorithms
C++ Templates L03 - Iterator 10 – Iterator.
10 – Iterators C++ Templates 4.6 The Iterator pgs
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Lecture 7-2 : STL Iterators
5.1 The Stack Abstract Data Type
L09 - Pokémon.
C++ Functions, Classes, and Templates
Lab 03 - Iterator.
Creation and Use of Namespaces
Templaets It is a new concept which enables us to define “generic class “ and “generic function” to provide the “ generic programming” We are familiar.
Data type List Definition:
Standard Template Library Find
Elements are always copied when they are put into a container
Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes.
Lists - I The List ADT.
Lists - I The List ADT.
C++ Templates L03 - Iterator 10 – Iterator.
Lecture 8-2 : STL Iterators and Algorithms
Parasol Lab, Texas A&M University
C++ Templates L03 - Iterator 10 – Iterator.
COP 3330 Object-oriented Programming in C++
Fundamental Programming
Pointers and dynamic objects
Standard Template Library
CMSC 202 Lesson 6 Functions II.
Lesson 25 Miscellaneous Topics
Modifying Objects Assignment operation Assignment conversions
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
CMSC 341 C++ and OOP.
An Introduction to STL.
Lecture 8: Introduction to C++ Templates and Exceptions
Chapter 3 Lists, Stacks, and Queues
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Presentation transcript:

Generic Algorithms (TIC++V2:C6) Yingcai Xiao 07/07/2008

What we are trying to achieve? To be able to write an algorithm that works with any type. Makes programs both simpler and safer. To customize algorithms at runtime. Standard Template Library (STL), a subset of the Standard C++ library, was originally designed around generic algorithms. Generic algorithms are code that process sequences of any type of values in a type-safe manner. The generic algorithms in the standard library provide a vocabulary with which to describe solutions. The goal is to use predefined algorithms for almost every task, instead of hand-coding loops every time you need to process a collection of data. To achieve this goal, we have to follow certain standards to create new types.

Function Templates (TIC++V2C5) A function template describes a family of functions. The syntax for creating either type of template is virtually identical, but they differ somewhat in how they are used. With function templates you can often omit the template arguments.

template<typename T> const T& min(const T& a, const T& b) { Function Template Example template<typename T> const T& min(const T& a, const T& b) {   return (a < b) ? a : b; } int z = min<int>(i, j); int z = min(i, j); double z = min(x, j); // x is a double

Function Template Example #include <string> #include <sstream>   template<typename T> T fromString(const std::string& s) {   std::istringstream is(s);   T t;   is >> t;   return t; } template<typename T> std::string toString(const T& t) {   std::ostringstream s;   s << t;   return s.str(); These function templates provide conversions to and from std::string for any types that provide a stream inserter or extractor, respectively. StringConv.h

Function Template Example int main() {   int i = 1234;   cout << "i == \"" << toString(i) << "\"" << endl;   float x = 567.89;   cout << "x == \"" << toString(x) << "\"" << endl;   complex<float> c(1.0, 2.0);   cout << "c == \"" << toString(c) << "\"" << endl;   cout << endl;     i = fromString<int>(string("1234"));   cout << "i == " << i << endl;   x = fromString<float>(string("567.89"));   cout << "x == " << x << endl;   c = fromString<complex<float> >(string("(1.0,2.0)"));   cout << "c == " << c << endl; StringConvTest.cpp

Function Template Example The output is what you’d expect: i == "1234" x == "567.89" c == "(1,2)"   i == 1234 x == 567.89 c == (1,2)

Function Template Example template<typename R, typename P> R implicit_cast(const P& p) {   return p; }   int main() {   int i = 1;   float x = implicit_cast<float>(i);   int j = implicit_cast<int>(x);   //! char* p = implicit_cast<char*>(i); } ///:~

Generic Algorithms

Generic Algorithms : copy #include <algorithm> #include <cassert> #include <cstddef>  // For size_t using namespace std;   int main() {   int a[] = { 10, 20, 30 };   const size_t SIZE = sizeof a / sizeof a[0];   int b[SIZE];   copy(a, a + SIZE, b);   for(size_t i = 0; i < SIZE; ++i)     assert(a[i] == b[i]); } ///:~ CopyInts.cpp

Generic Algorithms : copy #include <algorithm> #include <cassert> #include <cstddef> #include <string> using namespace std;   int main() {   string a[] = {"read", "my", "lips"};   const size_t SIZE = sizeof a / sizeof a[0];   string b[SIZE];   copy(a, a + SIZE, b); // deep copy, new strings are creared   assert(equal(a, a + SIZE, b)); } ///:~ CopyStrings.cpp

size_t: size for any types of varaibles. Generic Algorithms : copy size_t: size for any types of varaibles. sizeof: operator to compute the size (number of elements) of an array. copy is defined as a generic algorithm. assert(): design by contract copy anything Predicate: remove_copy_ifremove_copy_if

Generic Algorithms : copy template<typename T> void copy(T* begin, T* end, T* dest) {   while(begin != end)     *dest++ = *begin++;

Generic Algorithms : CopyVector.cpp #include <algorithm> #include <cassert> #include <cstddef> #include <vector> using namespace std;   int main() {   int a[] = { 10, 20, 30 };   const size_t SIZE = sizeof a / sizeof a[0];   vector<int> v1(a, a + SIZE);   vector<int> v2(SIZE);   copy(v1.begin(), v1.end(), v2.begin());   assert(equal(v1.begin(), v1.end(), v2.begin())); } ///:~ CopyVector.cpp

Generic Algorithms : Predicates #include <algorithm> #include <cstddef> #include <iostream> using namespace std;   // You supply this predicate bool gt15(int x) { return 15 < x; } int main() {   int a[] = { 10, 20, 30 };   const size_t SIZE = sizeof a / sizeof a[0];   int b[SIZE];   int* endb = remove_copy_if(a, a+SIZE, b, gt15);   int* beginb = b;   while(beginb != endb)     cout << *beginb++ << endl; // Prints 10 only } ///:~ CopyInts2.cpp