37
1 The Practice of Programming, CSIE@NTNU, Fall, 2009 Function Templates & STL Algorithms Instructor: Tsung-Che Chiang [email protected] Department of Computer Science and Information Engineering National Taiwan Normal University 2 Templates & STL,The Practice of Programming, CSIE@NTNU, 2009 Motivation Should we implement find() for every data type manually?

5 Templates & STL

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 5 Templates & STL

1

The Practice of Programming, CSIE@NTNU, Fall, 2009

Function Templates &STL Algorithms

Instructor: Tsung-Che [email protected]

Department of Computer Science and Information EngineeringNational Taiwan Normal University

2“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Motivation

Should we implement find() for everydata type manually?

Page 2: 5 Templates & STL

2

3“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

template <class T, class V>T find(T start, T end, V key){

while (start != end) {if (*start == key)

break;start++;

}

return start;}

Toward Function Templates

4“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Declarations and Definitions

template <class T1, class T2>void func(T1 v1, T2 v2) { T1 local; ... }

template <class T1>void func2(T1 *p) { ... }

template <class T1, typename T2>void func3(T1 v, T2 u) { ... }

template <class Type, class Type>Type wrong1(Type v1, Type v2) { ... }

template <class T1, T2>T1 *wrong2(const T2 &v1, const T2 &v2) { ... }

Page 3: 5 Templates & STL

3

5“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Declarations and Definitions

typedef double Type;template <class Type>Type func(Type a, Type b){

Type local;}template <class T>T func2(T a, T b){

typedef double T;}

The global Type is hidden inthe scope of func().

Error: redeclaration of templateparameter

template <class Type>inline Type func(Type a, Type b) { ... }

inline template <class Type> func2(Type a, Type b) { ... }

6“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Instantiation

Template instantiation takes place when thefunction template is called or when itsaddress is taken.

template <class T, class V>T find(T start, T end, V key){

while (start != end) {if (*start == key)

break;start++;

}

return start;}

int main(){int A[] = {1, 2, 3},

ptr = find(A, A+3, 2);

char * (*charfind)(char *, char *,char) = &find;

}

Page 4: 5 Templates & STL

4

7“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Argument Deduction

When a function template is called, types of templatearguments are determined according to the functionarguments. Note the return value of the function does not participate in

argument deduction.

template <class T>T func(T v1, T v2) { ... }

int main(){

func(10, 10);int num = func(2.3, 3.8); // argument T is “double”func(‘C’, ‘D’);func(“ABCD”, “EFGH”);func(10, 2.3); // argument deduction fails

}

8“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Argument Deduction

Type transformation allowed during argumentdeduction lvalue transformation

lvalue-to-rvalue array-to-pointer function-to-pointer

qualification transformation base class template transformation (not discussed

here)

Page 5: 5 Templates & STL

5

9“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Argument Deduction

Example: transformationtemplate <class T>T func(T *arr) { ... }

template <class T>T func2(const T *arr) { ... }

int main() {int *p, arr[10];

func(p);func(arr); // array-to-pointer transformation

func2(p); // qualification transformationfunc2(arr); // array-to-pointer & qualification trans.

}

10“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Explicit Template Arguments

First use: Resolve ambiguous template argument After template arguments are designated explicitly, all

implicit type conversion is allowed.

template <class T>T func(T v1, T v2) { ... }

int main() {

int num;float fnum;

func(num, fnum); // argument deduction fails

func<int>(num, fnum); // float-to-int transformationfunc<float>(num, fnum); // int-to-float transformation

}

Page 6: 5 Templates & STL

6

11“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

New Year Gift

For those who read this page, I am glad to give you aNew Year Gift.

Please write your concrete comments on this course(at least 200 words) and submit it to me before2010/1/22. Then, you will get a 2-point bonus on yourfinal score. Title: TPP09-Course comments

Please do not tell others, or the gift is not valuableany more.

12“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Explicit Template Arguments

Second use: Determine return type Like the default function argument, we can omit the template

arguments at the end of the list.

template <class T1, class T2, class T3>T1 func(T2 v1, T3 v2) { ... }

int main() {

int num;float fnum;

func(num, fnum); // T1 is not determined.func<int>(num, fnum);func<int, int, int>(num, fnum);func<int, , int>(num, fnum); // Only trailing arguments can

// be omitted.}

Page 7: 5 Templates & STL

7

13“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Compilation Model

Inclusion modelPut the definitions of function templates in the

header file, just as how we treat inline functions.

Separation model (Not every compiler supports it.)Put the declaration of function templates in the

header file and definitions in the implementationfile, just as how we treat non-inline functions.

Add “export”at the beginning of the definition ofthe function template.

14“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Recall the exercise we have done in theprevious class:

Writing a set of simple_sort() functions tosort CStudent.

Page 8: 5 Templates & STL

8

15“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

16“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Page 9: 5 Templates & STL

9

17“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

18“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Page 10: 5 Templates & STL

10

19“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

20“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Make your simple_sort() functions be functiontemplates so that they can deal with every kind ofdata type as the type supports operator < or acomparing function/functor.

std::sort as a reference

#include <algorithm>

template <class RandomAccessIterator>void sort(RandomAccessIterator first, RandomAccessIterator last);

template <class RandomAccessIterator, class Compare>void sort(RandomAccessIterator first, RandomAccessIterator last,

Compare comp);

Page 11: 5 Templates & STL

11

21“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

The version that uses operator <

22“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

The version that uses a comparing function/functor

Page 12: 5 Templates & STL

12

23“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Now you should know what std::sort cando for you and how it works.Certainly, std::sort realizes more efficient sort

algorithms, not the selection sort in our exercise.

The concept we learned in this exercise canbe generalized to (almost) all algorithms inC++ STL.

24“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

The STL Generic Algorithms

SearchSorting & orderingDeleting & replacingPermutationGenerationNumericRelational

Page 13: 5 Templates & STL

13

25“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Search Algorithms

Search count(), count_if() find(), find_if(), adjacent_find(),find_first_of()

search(), find_end()

Only for sorted range: binary_search() lower_bound(), upperbound(), equal_range()

26“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Search Algorithms- count()

3 12 1

Page 14: 5 Templates & STL

14

27“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Search Algorithms- count_if()

3 110

28“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Search Algorithms- binary_search()

Searching for 1: presentSearching for 2: presentSearching for 3: presentSearching for 4: not presentSearching for 5: presentSearching for 6: not presentSearching for 7: not presentSearching for 8: presentSearching for 9: not presentSearching for 10: not present

Page 15: 5 Templates & STL

15

29“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Search Algorithms- lower_bound()

Searching for 1: , pos = 0Searching for 2: , pos = 1Searching for 3: , pos = 2Searching for 4: , pos = 5Searching for 5: , pos = 5Searching for 6: , pos = 6Searching for 7: , pos = 6Searching for 8: , pos = 6Searching for 9: , pos = 7Searching for 10: , pos = 7

30“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Search Algorithms- upper_bound()

Searching for 1: , pos = 1Searching for 2: , pos = 2Searching for 3: , pos = 5Searching for 4: , pos = 5Searching for 5: , pos = 6Searching for 6: , pos = 6Searching for 7: , pos = 6Searching for 8: , pos = 7Searching for 9: , pos = 7Searching for 10: , pos = 7

Page 16: 5 Templates & STL

16

31“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Write a programAccept a sequence of chars as the input.Replace {a, e, i, o, u} with x.Output the encrypted sequence.

Use find_first_of()

32“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

Write a programAccept a sequence of sorted scores. Let the user input a certain score T. Tell him/her

how many students have scores lower than T. how many students have scores equal to T. how many students have scores no greater than T.

Use lower_bound(), equal_range(), andupper_bound().

Page 17: 5 Templates & STL

17

33“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Sorting & Ordering

Sorting & ordering sort(), stable_sort() partition(), stable_partition() nth_element() partial_sort() rotate() reverse() random_shuffle()

34“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Exercise

In the PoP Company, one engineer isresponsible for the cleaning job every day.They determine the order as follows:

Write a program to accept the input ofengineers’data and to print out the order fordoing the cleaning job.

Use partition(), sort(), partial_sort(), rotate(), reverse(),and random_shuffle().

The 5 richest male FemaleOther male

Random order The poorer the earlier. The younger the earlier.

Page 18: 5 Templates & STL

18

35“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Deleting & Replacing

Deleting & replacing remove(), remove_if() replace(), replace_if() unique() swap()

36“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Permutation Algorithms

Permutation next_permutation() prev_permutation()

Page 19: 5 Templates & STL

19

37“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Permutation- next_permutation()

1 2 31 3 22 1 32 3 13 1 23 2 11 2 3

38“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Generation Algorithms

Generation for_each() fill(), fill_n() generate(), generate_n() transform()

Page 20: 5 Templates & STL

20

39“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Generation Algorithms

Generation for_each() fill(), fill_n() generate(), generate_n() transform()

40“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Generation Algorithms

Generation for_each() fill(), fill_n() generate(), generate_n() transform()

Page 21: 5 Templates & STL

21

41“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

STL Algorithms

You can learn their functions easily through theexamples.

Just visit http://www.cplusplus.com/reference/algorithm/

The Practice of Programming, CSIE@NTNU, Fall, 2009

Class Templates & STLContainers

Instructor: Tsung-Che [email protected]

Department of Computer Science and Information EngineeringNational Taiwan Normal University

Page 22: 5 Templates & STL

22

43“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exercise

Write a class CIntArray with the following memberfunctions: CIntArray(int size)

so that the array size can be determined at runtime.

copy ctor, copy assignment, dtor size() begin(), end()

returns the address of the first element and the address ofthe next element to the last element

front(), back()returns the address of the first element and the address ofthe next element to the last element

operator []

44“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exerciseclass CIntArray{public:

CIntArray(int size = 0);CIntArray(const CIntArray &rhs);~CIntArray();int size() const { return size_; }

int *begin() { return arr_; }const int *begin() const { return arr_; }int *end() { return arr_+size_; }const int *end() const { return arr_+size_; }

int &front() { return arr_[0]; }const int &front() const { return arr_[0]; }int &back() { return arr_[size()-1]; }const int &back() const{ return arr_[size()-1]; }

int &operator [] (int index) { return arr_[index]; }const int &operator [] (int index) const { return arr_[index]; }

void swap(CIntArray &);CIntArray & operator = (const CIntArray &);

};

class CIntArray{private:

void init();int *arr_;int size_;

};

Page 23: 5 Templates & STL

23

45“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up ExerciseCIntArray::CIntArray(int size){

init();

if (size > 0) {arr_ = new int[size];size_ = size;

}}// ----------------------------------------------------CIntArray::CIntArray(const CIntArray &rhs){

init();

if (rhs.size() > 0) {arr_ = new int[rhs.size()];for (int i=0; i<rhs.size(); i+=1) {

(*this)[i] = rhs[i];}size_ = rhs.size();

}}// ----------------------------------------------------

void CIntArray::init() {arr_ = 0;size_ = 0;

}

46“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exercise

CIntArray::~CIntArray(){

delete [] arr_;}// ----------------------------------------------------void CIntArray::swap(CIntArray &rhs){

std::swap(this->arr_, rhs.arr_);std::swap(this->size_, rhs.size_);

}// ----------------------------------------------------CIntArray & CIntArray::operator = (const CIntArray &rhs){

CIntArray tmp(rhs);this->swap(tmp);

}// ----------------------------------------------------

Page 24: 5 Templates & STL

24

47“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exerciseint main(){

CIntArray empty;

cout << "Empty:";for (int i=0; i<empty.size(); i+=1) {

cout << empty[i];}

cout << "\nFixed:";CIntArray fixed(10);for (int i=0; i<fixed.size(); i+=1) {

fixed[i] = i*2; cout << fixed[i] << ' ';}cout << "front & back: " << fixed.front() << ',' << fixed.back();

cout << "\nRuntime:";CIntArray runtime(fixed[5]);for (int i=0; i<runtime.size(); i+=1) {

runtime[i] = i;cout << runtime[i] << ' ';

}... (next slide)

48“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exerciseint main(){

... (previous slide)cout << "\nCopy ctor:";CIntArray dup = runtime;for (int *p = dup.begin(); p!= dup.end(); p+=1) {

cout << *p << ' ';}

cout << "\nCopy assignment:";empty = fixed;for (int *p = empty.begin(); p!= empty.end(); p+=1) {

cout << *p << ' ';}

cout << "\nMemory leak: (Remark your destructor temporarily)\n";for (int i=0; i<10; i+=1) {

CIntArray memleak(1000*10000);for (int i=0; i<memleak.size(); i+=1) { memleak[i] = 0; }system("pause");

}

return 0;}

Page 25: 5 Templates & STL

25

49“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exercise

Usually, we also need a function to addelements one by one into the array.

Add a member function push_back().

int main(){

CIntArray test_push;for (int i=0; i<10; i+=1){

test_push.push_back(i);

cout << test_push[i] << ' ';}return 0;

}

50“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exercise

A slow version of push_back() Increase the size of array by 1 for each push_back()

operation.

void CIntArray::push_back_slow(const int &elem){

int *tmp = new int[size_+1];

for (int i=0; i<size_; i+=1){

tmp[i] = arr_[i];}tmp[size_] = elem;

size_ += 1;arr_ = tmp;

}

Page 26: 5 Templates & STL

26

51“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exercise

A more efficient implementation of push_back() Double the capacity of array when reallocation is needed.

void CIntArray::push_back(const int &elem){

if (size_ == capacity_){

int newcapa = capacity_>0?capacity_*2:1;int *tmp = new int[newcapa];

for (int i=0; i<size_; i+=1) {tmp[i] = arr_[i];

}

capacity_ = newcapa;arr_ = tmp;

}arr_[size_] = elem;size_ += 1;

}

class CIntArray{private:

void init();int *arr_;int size_, capacity_;

};

Remember to update all related memberfunctions after adding the new datamember.

52“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exerciseint main(){

cout << "\nSize vs. Capacity:\n";CIntArray sizetest;cout << "empty" << ' ' << sizetest.size()

<< ' ' << sizetest.capacity()<< std::endl;

for (int i=0; i<16; i+=1){

sizetest.push_back(i+100);//sizetest.push_back_slow(i+100);

cout << sizetest[i] << ' ' << sizetest.size()<< ' ' << sizetest.capacity()<< std::endl;

}

return 0;}

In push_back(), the cost of reallocation and move is amortized.

Page 27: 5 Templates & STL

27

53“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Warm-up Exercise

Member functions for “deleting”are left as homework: void clear()

All the elements of the vector are dropped: their destructors are called, andthen they are removed from the vector container, leaving the container witha size of 0.

void pop_back()Removes the last element in the vector, effectively reducing the vector sizeby one. This calls the removed element's destructor.

int * erase(int *ptr)Removes from the vector container a single element.

With the implementation using capacity_, doing push_back()after deleting actions is more efficient due to the saving ofreallocation cost.

54“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Toward Class Templates

Now we have a convenient dynamic array for storing“ints.”What about other data types such as char,float, double, and particularly, user-defined datatypes?

Do we have to write CCharArray, CFloatArray,and so on?

Thanks to C++, we have class templates!

Page 28: 5 Templates & STL

28

55“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Toward Class Templatestemplate <class TValue>class DynamicArray{public:

DynamicArray(int size = 0);DynamicArray(const DynamicArray &rhs);~DynamicArray();

TValue *begin() { return arr_; }const TValue *begin() const { return arr_; }TValue *end() { return arr_+size_; }const TValue *end() const { return arr_+size_; }

TValue &front() { return arr_[0]; }const TValue &front() const { return arr_[0]; }TValue &back() { return arr_[size()-1]; }const TValue &back() const{ return arr_[size()-1]; }

...private:

void init();TValue *arr_;int size_, capacity_;

};

The template parameter listis introduced.

56“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Toward Class Templates

template <class TVal>DynamicArray<TVal>::DynamicArray(int size) {

init();if (size > 0) {

arr_ = new TVal[size];size_ = capacity_ = size;

}}// ----------------------------------------------------template <class TVal>DynamicArray<TVal>::DynamicArray(const DynamicArray &rhs) {

init();

if (rhs.size() > 0){

arr_ = new TVal[rhs.size()];for (int i=0; i<rhs.size(); i+=1) {

(*this)[i] = rhs[i];}size_ = capacity_ = rhs.size();

}}

Page 29: 5 Templates & STL

29

57“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Toward Class Templates

int main(){

DynamicArray<int> arr1;for (int i=0; i<10; i+=1) {

arr1.push_back(i*3);}

DynamicArray<double> arr2(arr1.size());for (int i=0; i<arr1.size(); i+=1) {

arr2[i] = arr1[i]/8.0;}

DynamicArray<SomeObject> arr3;...for (int i=0; i<arr3.size(); i+=1) {

arr3[i].MemberFuncOfSomeObject();}

return 0;}

Instantiate a class by passingtemplate arguments, and thenenjoy it!

58“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Welcome, STL Containers!

Sequence vector (#include <vector>)

list (#include <list>)

Associate Containers set (#include <set>)

map (#include <map>)

Container Adaptor priority_queue (#include <queue>)

Page 30: 5 Templates & STL

30

59“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Construction

60“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Construction

Page 31: 5 Templates & STL

31

61“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Size & capacity

62“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Traversing elements

Page 32: 5 Templates & STL

32

63“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Assigning/inserting elements

0: 1 3 6 9 41: 9 9 92: 9 9 9 23: 5 9 9 9 24: 5 9 8 8 8 9 9 25: 5 9 8 8 8 9 9 1 3 6 26: 5 9 8 8 8 9 9 1 3 3 6 6 2

64“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Erasing elements

0: 1 2 3 4 5 6 7 8 9 101: 1 2 3 4 5 6 7 8 92: 1 2 3 4 6 7 8 93: 1 7 8 94:

Page 33: 5 Templates & STL

33

65“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Resizing

0: 1 1 1 1 1 [5,5]1: 1 1 1 1 1 0 0 0 0 0 [10,10]2: 1 1 1 [3,10]

66“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Reserving 0 01 12 23 44 45 86 87 88 89 160 101 102 103 104 105 106 107 108 109 10

Reserving is more efficient since it saves the cost of memory reallocation.Besides, it avoids the invalidation of pointers caused by memoryreallocation.

Page 34: 5 Templates & STL

34

67“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Comparisons

68“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Vector of vector (2-D dynamic array)

1 1 1 1 1 1 1 1 1 18 8 8 8 8

Page 35: 5 Templates & STL

35

69“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Vector of vector (2-D dynamic array)

Line 1:1Line 2:7 8 9 0 0Line 3:

70“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Vectors

Vector of vector (2-D dynamic array)

Please input number of rows and number of columns...>5 4Line 1:0 0 0 0Line 2:0 0 0 0Line 3:0 0 0 0Line 4:0 0 0 0Line 5:0 0 0 0

Page 36: 5 Templates & STL

36

71“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

STL Containers

You can learn their functions easily through theexamples.

Just visit http://www.cplusplus.com/reference/stl/

72“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

Boost Library

Page 37: 5 Templates & STL

37

73“Templates & STL,”The Practice of Programming, CSIE@NTNU, 2009

A Happy Ending of This Course

I am so glad to be the instructor of this course.Hope that all of you have learned more about

writing elegant and efficient C++ code.Please do keep practicing what you learned

in this semester.

Wish you have a Happy New Year!