Templates & STL 1.Generic Programming 2.C++ Templates 3.Function Templates 4.Class Templates 5.Standard Template Library (STL) 6.Vectors 7.Iterators 1.

Slides:



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

Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Starting Out with C++, 3 rd Edition 1 Chapter 16 – Exceptions, Templates, and the Standard Template Library (STL) Exceptions are used to signal errors.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Chapter 10.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
Standard Containers: Vectors
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
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.
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.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
Object Oriented Data Structures
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Templates and Polymorphism Generic functions and classes
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:
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
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,
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
Generic Programming Using the C++ Standard Template Library.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
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.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
Overview of C++ Templates
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
Template is a declaration (similar to class declaration), which deals with generic types. Templates are evaluated to produce concrete classes when a template-base.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
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++
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.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Introduction to Templates and Standard Template Library 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
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.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
Motivation for Generic Programming in C++
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
CSCE 210 Data Structures and Algorithms
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Templates.
ADT Implementations: Templates and Standard Containers
Exception Handling.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library
Standard Template Library
An Introduction to STL.
Presentation transcript:

Templates & STL 1.Generic Programming 2.C++ Templates 3.Function Templates 4.Class Templates 5.Standard Template Library (STL) 6.Vectors 7.Iterators 1

Generic programming Generic programming encourages: – Writing code without reference to a specific data type (float, int, etc.) – Designing code in the most “abstract” manner possible Why? – Trades a little extra design time for greatly improved re-usability 2

Generic programming Generalize algorithms – Sometimes called “lifting an algorithm” The aim (for the end user) is – Increased correctness Through better specification – Greater range of uses Possibilities for re-use – Better performance Through wider use of tuned libraries Unnecessarily slow code will eventually be thrown away G o from the concrete to the more abstract – The other way most often leads to bloat 3

Generic Programming Resources STL – Standard Template Library (Reference Pages ) GTL : Graph Template Library BGL : Boost Graph Library MTL : Matrix Template Library ITL : Iterative Template Library 4

Macros A macro (short for "macroinstruction", from Greek μακρο- 'long') in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to a replacement input sequence (also often a sequence of characters) according to a defined procedure. The mapping process that instantiates (transforms) a macro use into a specific sequence is known as macro expansion. A facility for writing macros may be provided as part of a software application or as a part of a programming language. In the former case, macros are used to make tasks using the application less repetitive. In the latter case, they are a tool that allows a programmer to enable code reuse or even to design domain-specific languages. 5

C++ Templates I always knew C++ templates were the work of the Devil, and now I'm sure... Part of the ongoing development of the C++ language Integral part of the larger C++ Standard Library (The Standard Template Library) C++ templates: "a clever kind of macro that obeys the scope, naming, and type rules of C++ ". A template describes a set of related classes or set of related functions in which a list of parameters in the declaration describe how the members of the set vary. The compiler generates new classes or functions when you supply arguments for these parameters; this process is called template instantiation. This class or function definition generated from a template and a set of template parameters is called a specialization. 6

C++ Templates Kinds of Templates  Function Permit the development of generic algorithms  Class Permit the development of generic objects 7

Overview of C++ Templates Templates are used to plug in different types – Can re-use same code with int, string, etc. Also called “type parameterization” – Types are given as parameters to a template – Like variables are given as a function’s parameters Can make templates for functions and classes – The user of a class template must declare the type parameters when declaring an instance – Don’t have to declare the type parameters when calling a function template (call as though a non-template function) The compiler figures it out for you, based on function call signature 8

Function Templates Function template: A pattern for creating definitions of functions that differ only in the type of data they manipulate Better than overloaded functions, since the code defining the algorithm of the function is only written once 9

Two functions that differ only in the type of the data they manipulate void swap(int &x, int &y) { int temp = x; x = y; y = temp; } void swap(char &x, char &y) { char temp = x; x = y; y = temp; } 10

A swap Template The logic of both functions can be captured with one template function definition template void swap(T &x, T &y) { T temp = x; x = y; y = temp; } 11

Using a Template Function When a function defined by a template is called, the compiler creates the actual definition from the template by inferring the type of the type parameters from the arguments in the call: int i = 1, j = 2; swap(i,j); This code makes the compiler instantiate the template with type int in place of the type parameter T 12

Function Template Notes A function template is a pattern No actual code is generated until the function named in the template is called A function template uses no memory When passing a class object to a function template, ensure that all operators referred to in the template are defined or overloaded in the class definition 13

Introduction to Function Templates template void swap(T &lhs, T &rhs) { T temp = lhs; lhs = rhs; rhs = temp; } int main () { int i = 3; int j = 7; swap (i,j); return 0; } Basic idea – same code is re-used for different types Function template swap – takes one type parameter, T Definition interchanges values of two passed arguments – of the parameterized type Compiler infers type is really int when swap is called Compiler instantiates the function template definition using type int 14

Function Templates A function template is a “generic” function that can work with any data type. The programmer writes the specifications of the function, but substitutes parameters for data types. When the compiler encounters a call to the function, it generates code to handle the specific data type(s) used in the call. This is not like inheritance. 15

An Example Function Template template T Min(const T &a, const T &b) { if (a < b) return a; else return b; } Indicates a template is being defined Indicates T is our formal template parameter Instantiated functions will return a value whose type is the actual template parameter Instantiated functions require two actual parameters of the same type. Their type will be the actual value for T 16

Template Example We want a function that prints out the values of an array. This function should work with arrays of type int, float, char, or string. In a perfect world (where all these types descended from the same base type), we could use inheritance to make this happen. 17

printArray.cpp – Program #include using namespace std; template void printArray ( const T *array, const int size ) { for ( int i = 0; i < size; i++ ) {if ( !( i % 10 ) ) cout << endl; cout << array[i] << " "; } // for cout << endl; } // printArray 18

printArray.cpp – Program (cont) void main ( void ) { const int aSize = 5, bSize = 7, cSize = 6, dSize = 3; int a[ aSize ] = { 1, 2, 3, 4, 5 }; float b[ bSize ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; char c[ cSize ] = "Hello"; string d[ dSize ] = { "I", "love", "CS" }; printArray( a, aSize ); printArray( b, bSize ); printArray( c, cSize ); printArray( d, dSize ); } // main 19

Generic swap Suppose we wanted a generic swap. template void swap ( T &var1, T &var2 ) { T temp; temp = var1; var1 = var2; var2 = temp; } // swap 20

Suppose we want a generic Max function template T maximum(T a, T b) { return a > b ? a : b ; // Familiar operator? } void main() { cout << "max(10, 15) = " << maximum(10, 15) << endl ; cout << "max('k', 's') = " << maximum('k', 's') << endl ; cout << "max(10.1, 15.2) = " << maximum(10.1, 15.2) << endl ; } 21

Generic Sorting template void InsertionSort(T A[], int n) { for (int i = 1; i < n; ++i) { if (A[i] < A[i-1]) { T val = A[i]; int j = i; do { A[j] = A[j-1]; --j; } while ((j > 0) && (val < A[j-1])); A[j] = val; } 22

STL’s Template Functions STL provides template definitions for many programming tasks  Use them! Do not reinvent the wheel! Searching and sorting  find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort() Comparing  equal() Rearranging and copying  unique(), replace(), copy(), remove(), reverse(), random_shuffle(), merge() Iterating  for_each() 23

Function Templates 24 Example of a Function Template Declaration: // Returns the minimum of array x[ ]. The data // type of x[ ] is arbitrary & customizable template T min(T x[], int length){ T m = x[0];// m is the minimum so far for (int i=1;i<n;i++) if (x[i]<m) m=x[i]; return m; } Example of Use: int x[]= {11, 13, 5, 7, 4, 10}; double y[]= {4.5, 7.13, 17}; int minx = min (x,6); double miny= min (y,3);

Class Templates It is possible to define templates for classes. Unlike functions, a class template is instantiated by supplying the type name ( int, float, string, etc.) at object definition 25

Class Template Consider the following classes 1.Class used to join two integers by adding them: class Joiner { public: int combine(int x, int y) {return x + y;} }; 2.Class used to join two strings by concatenating them: class Joiner { public: string combine(string x, string y) {return x + y;} }; 26

Example class Template A single class template can capture the logic of both classes: it is written with a template prefix that specifies the data type parameters: template class Joiner { public: T combine(T x, T y) {return x + y;} }; 27

Using Class Templates To create an object of a class defined by a template, specify the actual parameters for the formal data types Joiner jd; Joiner sd; cout << jd.combine(3.0, 5.0); cout << sd.combine("Hi ", "Ho"); Prints 8.0 and Hi Ho 28

Introduction to Class Templates template class Array { public: Array(const int size); ~Array(); private: T * values_; const int size_; }; int main() { Array a(10); Array b(5); return 0; } Parameterized type T must be specified in class template declaration – Both as a parameter, and where it’s used in the class When an instance is declared, must also explicitly specify the concrete type parameter – E.g., int vs. string in function main() – In previous function template example, didn’t have to say swap 29

Tips on Using Function and Class Templates Push common code and variables up into non-template base classes – Gives compiler less work to do instantiating templates – Reduces program size and compilation time Use function templates when you want type parameterization to be “invisible” to programmer – To force an explicit declaration of the parameterized type, use member functions of class templates instead Use class templates when you want to parameterize member variables types – Lots of containers in the STL do this (vector, list, etc.) – We’ll talk about the STL and how it uses templates later in the semester 30

Introduction to the Standard Template Library Standard Template Library (STL): a library containing templates for frequently used data structures and useful algorithms Programs can be developed faster and are more portable if they use templates from the STL An ISO C++ standard framework of about 10 containers and about 60 algorithms connected by iterators – Other organizations provide more containers and algorithms in the style of the STL Boost.org, Microsoft, SGI, … Probably the currently best known and most widely used example of generic programming 31

The Standard Template Library (STL) is a software library included in the C++ Standard Library. It provides containers, iterators, and algorithms. More specifically the C++ Standard Library is based on the STL Library published by SGI. Both include some features not found in the other. SGI's STL is rigidly specified as a set of headers, while ISO C++ does not specify header content, and allows implementation either in the headers, or in a true library. STL was architected by Alexander Stepanov in Standard Template Library 32

Introduction The C++ Standard Template Library (STL) has become part of C++ standard The main author of STL is Alexander Stephanov He chose C++ because of templates and no requirement of using OOP! The library is somewhat unrelated with the rest of the standard library which is OO

3D generic world ALGORITHMS DATA STRUCTURES ITERATORS Stephanov observed three orthogonal dimensions in algorithms: iterators allow algorithms to iterate over data structures. Iterators are very akin with C pointers and compatible with them

35

The quality of the C++ compiler has a large impact on usability of STL: Error messages involving templates are difficult to decipher. Excessive usage of STL templates leads to code bloat. Template instantiation tends to increase compilation time and memory usage (sometimes by as much as an order of magnitude). STL implementations non-standardized. STL Disadvantages 36

The three parts of STL Containers Algorithms Iterators 37

Standard Template Library Two important types of data structures in the STL: – containers: classes that store data and impose some organization on it OR a class that stores data and organizes it in some fashion. – iterators: like pointers; provides mechanisms for accessing elements in a container OR similar to a pointer and is used to access the individual data elements in a container. 38

Containers What are they? Containers are objects that hold other objects. Two types of container classes in STL: – sequential containers: organize and access data sequentially, as in an array. These include vector, dequeue, and list containers. – associative containers: use keys to allow data elements to be quickly accessed (allowing efficient retrieval of values based on keys). These include set, multiset, map, and multimap containers. 39

Creating Container Objects To create a list of int, write list mylist; To create a vector of string objects, write vector myvector; Requires the vector header file 40

Iterators (1) We need a subscript operator to access container elements BUT … in a generic way – STL provides objects called iterators – can point at an element – can access the value within that element – can move from one element to another They are independent of any particular container … thus a generic mechanism 41

Iterators (2) Generalization of pointers, used to access information in containers Four types: – forward (uses ++ ) – bidirectional (uses ++ and -- ) – random-access – input (can be used with cin and istream objects) – output (can be used with cout and ostream objects) 42

Iterators Given a vector which has had values placed in the first 4 locations: v.begin() will return the iterator value for the first slot, v.end() for the next empty slot vector v v.begin() v.end()

Iterators Each STL container declares an iterator type – can be used to define iterator objects To declare an iterator object – the identifier iterator must be preceded by name of container scope operator :: Example: vector :: iterator vecIter = v.begin() 44

Containers and Iterators Each container class defines an iterator type, used to access its contents The type of an iterator is determined by the type of the container: list ::iterator x; list ::iterator y; x is an iterator for a container of type list 45

Containers and Iterators Each container class defines functions that return iterators: begin(): returns iterator to item at start end(): returns iterator denoting end of container 46

Containers and Iterators Iterators support pointer-like operations: if iter is an iterator: – *iter is the item it points to: this dereferences the iterator – iter++ advances to the next item in the container – iter-- backs up in the container The end() iterator points to past the end: it should never be dereferenced 47

Traversing a Container Given a vector: vector v; for (int k=1; k<= 5; k++) v.push_back(k*k); Traverse it using iterators: vector ::iterator iter = v.begin(); while (iter != v.end()) { cout << *iter << " "; iter++} Prints

Algorithms STL contains algorithms implemented as function templates to perform operations on containers. Requires algorithm header file Collection of algorithms includes binary_searchcount for_eachfind max_elementmin_element random_shufflesort and others 49

Using STL algorithms Many STL algorithms manipulate portions of STL containers specified by a begin and end iterator max_element(iter1, iter2) finds max element in the portion of a container delimited by iter1, iter2 min_element(iter1, iter2) is similar to above 50

More STL algorithms random_shuffle(iter1, iter2) randomly reorders the portion of the container in the given range sort(iter1, iter2) sorts the portion of the container specified by the given range 51

random-shuffle Example The following example stores the squares 1, 4, 9, 16, 25 in a vector, shuffles the vector, and then prints it out. int main() { vector vec; for (int k = 1; k <= 5; k++) vec.push_back(k*k); random_shuffle(vec.begin(),vec.end()); vector ::iterator p = vec.begin(); while (p != vec.end()) { cout << *p << " "; p++; } return 0; } 52

Basic model Algorithms sort, find, search, copy, … Containers vector, list, map, hash_map, … 53 iterators Separation of concerns –Algorithms manipulate data, but don’t know about containers –Containers store data, but don’t know about algorithms –Algorithms and containers interact through iterators Each container has its own iterator types

Containers (hold sequences in difference ways) vector list (doubly linked) set (a kind of tree)

Basic model A pair of iterators define a sequence – The beginning (points to the first element – if any) – The end (points to the one-beyond-the-last element) 55 … begin:end: An iterator is a type that supports the “iterator operations” ++ Go to next element * Get value == Does this iterator point to the same element as that iterator? Some iterators support more operations (e.g. --, +, and [ ])

Vectors Holds a set of elements, like an array Vectors are dynamic arrays: arrays that can grow as needed. Flexible number of elements – can grow and shrink, – No need to specify size when defined – Automatically adds more space as needed When using the vector type the required header to be included is 56

vectorConstructor. assignErases a vector and copies the specified elements to the empty vector. atReturns a reference to the element at a specified location in the vector. backReturns a reference to the last element of the vector. beginReturns a random-access iterator to the first element in the container. capacityReturns the number of elements that the vector could contain without reallocating. clearErases the elements of the vector. emptyTests if the vector container is empty. endReturns a random-access iterator that points just beyond the end of the vector. eraseRemoves an element or a range of elements in a vector from specified positions. frontReturns a reference to the first element in a vector. insertInserts an element or a number of elements into the vector at a specified position. max_sizeReturns the maximum length of the vector. pop_backDeletes the element at the end of the vector. push_backAdd an element to the end of the vector. rbeginReturns an iterator to the first element in a reversed vector. rendReturns an iterator to the end of a reversed vector. resizeSpecifies a new size for a vector. reserveReserves a minimum length of storage for a vector object. sizeReturns the number of elements in the vector. swapExchanges the elements of two vectors. STL vector Members 57

58 Vector class Can hold values of any type Type is specified when a vector is defined vector scores; vector volume; Declaring/ defining a vector: vector scores; // starts with 0 elements vector scores(30); // int vector with initial size 30 elements vector scores(20,0); // define 20-element int vector and initialize all to 0 vector scores(final); // define int vector initialized to size and contents of vector final Can use [ ] to access elements

59 // display original size of v cout<<"Size = "<<v.size()<<endl; /* put values onto end of a vector; the vector will grow as needed */ for(i=0; i<10; ++i) v.push_back(i); // change contents of a vector for(i=0; i<v.size(); ++i) v[i] = v[i] + v[i]; // access using subscripting for(i=0; i<10; ++i) cout <<v[i]<<" "; cout << endl; // access via iterator vector ::iterator p = v.begin(); while(p != v.end()) { cout << *p << " "; ++p; } Using a vector

Vector - examples vector v; for(int i = 1; i < ; i *= 2) { v.push_back(i); } int elements_count = v.size(); vector v(20); for(int i = 0; i < 20; i++) { v[i] = i+1; } v.resize(25); for(int i = 20; i < 25; i++) { v[i] = i*2; } vector v(20); for(int i = 0; i < 20; i++) { v[i] = i+1; } v.resize(25); for(int i = 20; i < 25; i++) { v.push_back(i*2); // Writes to elements with indices [25..30), not [20..25) ! < } 60

Growing a Vector’s Size Use push_back member function to add an element to a full array or to an array that had no defined size scores.push_back(75); Use size member function to determine number of elements currently in a vector vec_size=scores.size(); 61

Remove vector elements Use pop_back member function to remove last element from vector scores.pop_back(); To remove all contnets of vector, use clear member function scores.clear(); To determine if vector is empty, use empty member function while (!scores.empty()) …. 62

Vector Subscripts 01: #include 02: #include 03: 04: using namespace std; 05: 06: int main() { 08: vector salaries; 09: bool more = true; 10: while (more) { 12: double s; 13: cout > s; 15: if (s == 0) 16: more = false; 17: else 18: salaries.push_back(s); 19: } 20: 21: double highest = salaries[0]; 22: int i; 23: for (i = 1; i highest) 25: highest = salaries[i]; 26: 27: for (i = 0; i < salaries.size(); i++) { 29: if (salaries[i] == highest) 30: cout "; 31: cout << salaries[i] << "\n"; 32: } 34: return 0; 35: } 63

Vector Parameters and Return Values (Vector Parameters) Functions and procedures often have vector parameters. Example: double average(vector v) { if (v.size() == 0) return 0; double sum = 0; for (int i = 0; i < v.size(); i++) sum = sum + v[i]; return sum / v.size(); } A vector can be passed by value or by reference. Pass by reference is used for modifying individual elements of the vector. Example: void raise_by_percent(vector & v, double p){ for (int i = 0; i < v.size(); i++) v[i] =v[i] * (1 + p / 100); } 64

Vector Parameters and Return Values (Return Values) A function can return a vector. Here is a function that collects all values that fall within a certain range. vector between(vector v, double low, double high){ vector result; for (int i = 0; i < v.size(); i++) if (low <= v[i] && v[i] <= high) result.push_back(v[i]); return result; } 65

Vector Parameters and Return Values (matches.cpp) 25: int main() { 27: vector salaries(5); 28: salaries[0] = ; 29: salaries[1] = ; 30: salaries[2] = ; 31: salaries[3] = ; 32: salaries[4] = ; 33: 34: vector matches = find_all_between(salaries, , ); 36: 37: for (int j = 0; j < matches.size(); j++) 38: cout << salaries[matches[j]] << "\n"; 39: return 0; 40: } 66

Vector Parameters and Return Values (Return Values) (cont.) Here is a function that collects the positions of all matching values in a vector of integers. vector find_all_between(vector v, double low, double high){ vector pos; for (int i = 0; i < v.size(); i++) { if (low <= v[i] && v[i] <= high) pos.push_back(i); } return pos; } 67

Other Useful Member Functions Member Function DescriptionExample at(elt) Returns the value of the element at position elt in the vector cout << vec1.at(i); capacity() Returns the maximum number of elements a vector can store without allocating more memory maxelts = vec1.capacity(); reverse() Reverse the order of the elements in a vector vec1.reverse(); resize (elts,val) Add elements to a vector, optionally initializes them vec1.resize(5,0); swap(vec2) Exchange the contents of two vectors vec1.swap(vec2); 68

Example (vectors & iterators) Write a program that read integers from the user, sorts them, and print the result. Solving the problem – Easy way to read input. – A “place” to store the input – A way to sort the stored input. 69

Using STL int main() { int input; vector ivec; //input data while ( cin >> input ) ivec.push_back(input); } 70

STL - Sorting sort(ivec.begin(), ivec.end()); Sort Prototype: void sort(Iterator first, Iterator last); 71

STL - Output for ( int i = 0; i < ivec.size(); ++i ) cout << ivec[i] << " "; cout << endl; vector ::iterator it; for ( it = ivec.begin(); it != ivec.end(); ++it ) cout << *it << " "; cout << endl; Or (more recommended) 72

STL - Include files #include // I/O #include // container #include // sorting using namespace std; 73

Putting it all together void main() { int input; vector ivec; // input while (cin >> input ) ivec.push_back(input); // sorting sort(ivec.begin(), ivec.end()); // output vector ::iterator it; for ( it = ivec.begin(); it != ivec.end(); ++it ) { cout << *it << " "; } cout << endl; } 74