The function find. Template function find

Similar documents
Input file: Fundamentals of Software Engineering Applicators, Manipulators, and Function Objects An introduction to the Standard Template Library

The Standard Template Library. An introduction

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

pointers & references

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

Due Date: See Blackboard

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

STL: C++ Standard Library

Chapter 15 - C++ As A "Better C"

CPSC 427a: Object-Oriented Programming

Chapter 5. The Standard Template Library.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Module 9. Templates & STL

Object oriented programming

C++ Standard Template Library

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

Lecture-5. STL Containers & Iterators

G52CPP C++ Programming Lecture 18

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

COEN244: Class & function templates

CS197c: Programming in C++

Function Templates. Consider the following function:

Programming with Haiku

Lecture 2. Binary Trees & Implementations. Yusuf Pisan

C++ Modern and Lucid C++ for Professional Programmers

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Fast Introduction to Object Oriented Programming and C++

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Introduction to C++ Systems Programming

Working with Batches of Data

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors

Strings and Stream I/O

Chapter 2. Procedural Programming

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

CS

MODULE 35 --THE STL-- ALGORITHM PART III

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

A <Basic> C++ Course

Unit 4 Basic Collections

Comp151. Generic Programming: Container Classes

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

AN OVERVIEW OF C++ 1

A <Basic> C++ Course

CS 376b Computer Vision

use static size for this buffer

Short Notes of CS201

Object-Oriented Programming for Scientific Computing

Computational Physics

CS201 - Introduction to Programming Glossary By

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Set Implementation Version 1

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Programming in C++ using STL. Rex Jaeschke

More Advanced Class Concepts

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.

CS242 COMPUTER PROGRAMMING

STL. Zoltán Porkoláb: C++11/14 1

Arrays. Week 4. Assylbek Jumagaliyev

Linked List using a Sentinel

C++_ MARKS 40 MIN

Standard Library Reference

Outline. Function calls and results Returning objects by value. return value optimization (RVO) Call by reference or by value?

CS 7B - Spring Final Exam

EAS 230 Fall 2002 Section B

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Use the dot operator to access a member of a specific object.

Standard Library. Lecture 27. Containers. STL Containers. Standard Library

Lab 2: ADT Design & Implementation

SETS AND MAPS. Chapter 9

Generic Programming in C++: A modest example

Operator Overloading in C++ Systems Programming

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

CS11 Advanced C++ Fall Lecture 1

Major Language Changes, pt. 1

CSI33 Data Structures

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

CS193D Handout 12 Winter 2005/2006 January 30, 2006 Introduction to Templates and The STL

Lecture 5 Files and Streams

CSCI-1200 Data Structures Fall 2009 Lecture 20 Hash Tables, Part II

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

File I/O Christian Schumacher, Info1 D-MAVT 2013

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Computer Science II Lecture 2 Strings, Vectors and Recursion

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

Summary of basic C++-commands

A brief introduction to C++

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

PENN STATE UNIVERSITY Department of Economics

Transcription:

The function find // Function to find a given value in an array of integers int find (int a[], // Array being searched int n, // Size of the array int t) // Target value // This function will return the smallest index within a that // contains t. If t is not found, n will be returned. int i; for (i = 0; i < n && a[i]!= t; i++) ; return i; 1 Template function find // Template function to find a given value in an array template<class T> int find (T a[], // Array being searched int n, // Size of the array T t) // Target value // This function will return the smallest index within a that // contains t. If t is not found, n will be returned. int i; for (i = 0; i < n && a[i]!= t; i++) ; return i; 2

Containers and Iterators A container is a class that holds objects. An iterator is a class whose objects behave like pointers. If cont is a container holding objects of class T and itr is an iterator associated with that container, then *itr is a value of type T which is stored in cont *++itr is a value of type T which is stored in cont following the value *itr. *--itr is a value of type T which is stored in cont before the value *itr. 3 Function find using iterators // Template function to find a given value in a container template< class iterator, class T > iterator find (iterator b, // place to start iterator e, // place to end const T& t) // Target value // This function will return the first iterator in the range // [b,e) that points to t. // If t is not found, e will be returned. iterator p = b; for (; p!= e && *p!= t; p++) ; return p; 4

The standard library The ANSI/ISO C++ standard defines a library of containers, iterators, and algorithms *. The algorithms are defined to take iterators as arguments, and will work on any container that provides the appropriate iterator. * This library is based upon the work of Alesander Stepanov and Meng Lee 5 Containers Sequences vector list deque A sequence is a kind of container that organizes a finite set of objects, all of the same type, into a strictly linear arrangement. supports random access iterators constant time insert and erase at the end insert and erase in the middle take linear time supports bidirectional iterators constant time insert an erase anywhere within the sequence supports random access iterators constant time insert and erase at both begin and end linear time insert and erase in the middle. 6

Associative containers set mulitset map multimap fast retrieval of data based on keys unique keys supports retrieval of the keys themselves multiple copies of the same key supports retrieval of the keys themselves unique keys supports retrieval of values of another type based on the keys. multiple copies of the same key supports retrieval of values of another type based on the keys 7 Common functions for containers (selected list) X is a container containing objects of type T X::value_type Returns the type T X::reference Returns the type T& X::pointer Returns the type T* X::iterator X u X(a) X u(a) X u = a (&a)->~x() a.begin() Returns the iterator type supported by the container pointing to objects of type T& Declares u to be an object of type X, initially empty. Copy constructor Explicit call to the destructor. The destructor is applied to every element of a and all memory is returned. An iterator pointing to the beginning of the container. 8

a.end() An iterator pointing just past the end of the container. Note that *(a.end()) is not defined, but x == a.end() is defined. a.size() The number of objects currently contained in a. a.capacity() a.reserve (size_type n) The number of objects for which space is reserved. Set the capacity to n. 9 Functions common to sequences (selected list) a.insert(p,t) Inserts object t into the container a before the item pointed to by p. a.erase(p) Removes the object pointed to by p. a.front() a.back() a.push_front(t) *a.begin() the value of the first item. *(--a.end()) the value of the last item. a.insert(a.begin(),t) not defined for vector a.push_back(t) a.insert(a.end(), t) a.pop_front() a.pop_back() a[i] a.erase(a.begin()) not defined for vector a.erase(--a.end()) *(a.begin() + n) not defined for list Note: whenever an item is inserted, and the insertion makes size greater than capacity, reserve is automatically called to increase capacity. 10

rvalues vs.lvalues An rvalue is a value that can occur on the right side of an assignment operation. It may be a temporary object. An lvalue is a value that can occur on the left side of an assignment. It is a reference to an object. 11 Iterators input iterator output iterator *r is an rvalue, but not an lvalue ++r and r++ are defined Algorithms on input iterators should never pass through the same iterator twice. *r is an lvalue, but not an rvalue ++r and r++ are defined Algorithms on input iterators should never pass throught the same iterator twice. forward iterator *r is both an lvalue and an rvalue ++r and r++ are defined Algorithms may be multi-pass. Bidirectional iterators Random access iterators Same as forward iterators --r and r-- are also defined Same as bidirectional iterators a[n] is defined to be *(a + n) An iterator lower on the above list may be used in an algorithm that requires one higher on the list 12

for_each find find_if adjacent_find count copy swap transform Algorithms (selected list) Applies a function to each element of a sequence. This function is not expected to modify the values of the sequence. Finds an element of a given value in a sequence Finds an element satisfying a given condition in a sequence Find the the first occurance of adjacent equal values, or adjacent values both satisfying a given condition. Counts the number of items in a sequence of a given value or satisfying a given condition Copies one sequence to another. Swaps the values stored at two locations Applies a function to each element of a sequence, making a copy. The destination may be equal to the source. 13 // FILE: ex_3_8_3 // Example from section 3.8.3 from Stroustrup's 3rd edition #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <string> int main(int argc, char* argv[]) using namespace std; if (argc!= 3) return 1; ifstream is(argv[1]); istream_iterator<string> ii(is); istream_iterator<string> eos; vector<string> b; copy (ii, eos, back_inserter(b)); sort(b.begin(), b.end()); ofstream os(argv[2]); ostream_iterator<string> oo(os, "\n"); unique_copy(b.begin(), b.end(), oo); return!is &&!os; 14

Function Objects Function objects are objects with operator() defined. They are used to pass a function to another function. Example: the function find_if is defined as follows: template <class InputIterator, class Predicate> InputIterator find_if (InputIterator first, InputIterator last, Predicate pred) while (first!= last &&!pred(*first)) ++first; return first; The class Predicate could be replaced by the following: struct greater_than_int_x int t; greater_than_int_x(int _t) :t(_t) bool operator()(int x)return x > t; ; 15 Template Selection Sort using Iterators and Function Objects // FILE selsort.h // SORTS THE INPUT ARRAY USING THE SELECTION SORT ALGORITHM #include <algorithm> using std::swap; template <class iterator, class comp> void sort (iterator b, // points to beginning of container to be sorted iterator e, // points to one past the end of the container comp c) // comparison operator // LOCAL DATA iterator pmin; // pointer to each smallest item located // by min_element iterator pi; // loop index iterator em = e; // pointer to last item in container em--; 16

for (pi=b; pi!= em; pi++) // Invariant: the elements in [b, pi) are in their proper // place and pi!= em. pmin = find_min(pi, e, c); swap (*pmin, *pi); // end for // end sel_sort 17 template< class iterator, class condition > iterator find_min (iterator b, // place to start iterator e, // place to end condition c) // condition to be satisfied // This function will return the iterator which points to the // "smallest" item in the range [b,e) which satisfies c if (b == e) return b; iterator r = b; while (++b!= e) if (c(*b, *r)) r = b; return r; 18

Finding Palindrome A palindrome is a string which reads the same way from left to right and right to left. Example: the words civic and rotator are palindromes. bool ispalindrome_type1(string& astring) string temp(astring); reverse(temp.begin(), temp.end()); return temp == astring; What about Rats Live on No Evil Star 19 bool ispalindrome_type2(string& astring) string alllow(astring); transform(astring.begin(), astring.end(), alllow.begin(), tolower); return ispalindrome_type1(alllow); The template function transform is defined as follows: template <class input_iterator, class output_iterator, class FUN> output_iterator transform (input_iterator b, input_iterator e, output_iterator o, FUN f) while (b!= e) *o++ = f(*b++); return o; 20

What about I Love Me, Vol. I. bool ispalindrome_type3(string& astring) string punctchars = ",.:;!?\'\""; string temp = remove_all(astring, punctchars); return ispalindrome_type2(temp); string remove_all(string& text, const string& spaces) string result(text); string::iterator i = remove_copy_if(text.begin(), text.end(), result.begin(), is_member(spaces)); result.erase(i, result.end()); return result; 21 class is_member public: explicit is_member(const string& s) : target(s) bool operator()(char c) return target.find_first_of(c)!= string::npos; private: string target; ; template<class input_iterator, class output_iterator, class FUN> output_iterator remove_copy_if (input_iterator b, input_iterator e, output_iterator o, FUN f) while (b!= e) if (!f(*b)) *o++ = *b++; else ++b; return o; 22

Sets, Multisets, Maps, and Multimaps A set is a container designed to contain unique objects. A comparison operation that defines a total order must be provided. Internally the objects are maintained in order and the find operation is optimized (O(log n) A multiset is like the set except that the requirement for uniqueness of the objects is eliminated. A map is a set of pairs. The left element of the pair, also called the key, is required to be unique. The operator[] is defined on the map such that the key may be used as an index. This is also known as an associative array. A multimap is a map except that the requirement for uniqueness of the keys is eliminated. 23 // FILE: ex_3_8_3 // Example from section 3.8.3 from Stroustrup's 3rd edition // Revised to use the set class #pragma warning (disable:4786) #include <iostream> #include <fstream> #include <algorithm> #include <set> #include <string> int main(int argc, char* argv[]) using namespace std; if (argc!= 3) return 1; ifstream is(argv[1]); istream_iterator<string> ii(is); istream_iterator<string> eos; set<string> b; copy (ii, eos, inserter(b, b.begin())); ofstream os(argv[2]); ostream_iterator<string> oo(os, "\n"); copy(b.begin(), b.end(), oo); return!is &&!os; 24

// FILE: find_words // Program to find all of the words in a text. #pragma warning (disable:4786) #include <iostream> #include <fstream> #include <algorithm> #include <set> #include <vector> #include <string> #include <ctype.h> using namespace std; class is_member public: explicit is_member(const string& s) : target(s) bool operator()(char c) return target.find_first_of(c)!= string::npos; private: string target; ; 25 string remove_all(const string& text, const string& spaces) string result(text); string::iterator i = remove_copy_if(text.begin(), text.end(), result.begin(), is_member(spaces)); result.erase(i, result.end()); return result; string makeword(const string& s) string punctchars = ",.:;!?\'\""; string temp = remove_all(s, punctchars); transform(temp.begin(), temp.end(), temp.begin(), tolower); return temp; 26

int main(int argc, char* argv[]) if (argc!= 3) return 1; ifstream is(argv[1]); istream_iterator<string> ii(is); istream_iterator<string> eos; set<string> b; transform (ii, eos, inserter(b, b.begin()), makeword); ofstream os(argv[2]); ostream_iterator<string> oo(os, "\n"); copy(b.begin(), b.end(), oo); return!is &&!os; 27 // FILE: countwds.cpp // Program to count the occurances of words #pragma warning (disable:4786) #include <iostream> #include <fstream> #include <algorithm> #include <map> #include <vector> #include <string> #include <utility> using namespace std; typedef pair<string, int> mypair; ostream& operator<<(ostream& os, const mypair& mp) os << mp.first << '\t' << mp.second; return os; 28

int main(int argc, char* argv[]) if (argc!= 3) return 1; ifstream is(argv[1]); istream_iterator<string> ii(is); istream_iterator<string> eos; map<string, int> b; for (; ii!= eos; ++ii) ++b[makeword(*ii)]; ofstream os(argv[2]); ostream_iterator<mypair> oo(os, "\n"); copy(b.begin(), b.end(), oo); return!is &&!os; 29 // kwic.cpp // the KWIC program // Georg Trausmuth, May 1995 // Modified by Paul Wolfgang to conform to the latest standard // and to work around a limitation in Microsoft C++ #pragma warning( disable : 4786) #include <iostream> #include <fstream> #include <utility> #include <list> #include <map> #include <algorithm> #include <vector> using namespace std; typedef vector<char> my_string; typedef multimap<my_string, my_string*, less<my_string> > permutedtitles_t; typedef list<my_string> Titles_t; typedef permutedtitles_t::value_type TitlesPair_t; 30

inline istream& operator>>(istream& istr, my_string& mystr) mystr.erase(mystr.begin(), mystr.end()); char ch; istr.get(ch); while (istr && ch!= '\n') mystr.push_back(ch); istr.get(ch); return istr; inline ostream& operator<<(ostream& ostr, const my_string& mystr) my_string::const_iterator si; for (si = mystr.begin(); si!= mystr.end(); ostr << *si++) ; return ostr; 31 class permute public: permute() : str('\0'), pos(0) permute(const my_string& s) : str(s), pos(str.begin()) my_string operator*() if((pos == str.begin()) (pos == 0)) return str; my_string ret; copy(pos+1, str.end(), back_inserter(ret)); ret.push_back(' '); copy(str.begin(), pos, back_inserter(ret)); return ret; permute& operator++() if((pos!= 0) && (pos!= str.end())) pos = find(pos+1, str.end(), ' '); if(pos == str.end()) pos = 0; return *this; permute operator++(int) permute p = *this; operator++(); return p; 32

friend bool operator==(const permute& p, const permute& q); private: my_string str; my_string::iterator pos; ; inline bool operator==(const permute& p, const permute& q) return((&p == &q) ((p.pos == 0) && (q.pos == 0))); class CircularShift public: CircularShift(permutedTitles_t& store) : index(store) void operator()(my_string& str) for (permute x(str);!(x == permute()); x++) index.insert(titlespair_t(*x, &str)); private: permutedtitles_t& index; ; 33 inline ostream& operator<<(ostream& out, const TitlesPair_t& p) return out << p.first << ":\n\t" << (*(p.second)) << endl; int main (int argc, char* argv[]) Titles_t titles; permutedtitles_t KWICindex; istream_iterator<my_string> ii(cin); istream_iterator<my_string> eos; copy(ii, eos, back_inserter(titles)); for_each(titles.begin(), titles.end(), CircularShift(KWICindex)); ostream_iterator<titlespair_t> oo(cout); copy(kwicindex.begin(), KWICindex.end(),oo); return 0; 34

Output of KWIC 3rd edition The Programming Language C++: The Programming Language C++ 3rd edition C++ 3rd edition The Programming Language: The Programming Language C++ 3rd edition C++ The Design and Evolution of: The Design and Evolution of C++ Design and Evolution of C++ The: The Design and Evolution of C++ Evolution of C++ The Design and: The Design and Evolution of C++ Introduction to the Standard Template Library: Introduction to the Standard Template Library Language C++ 3rd edition The Programming: The Programming Language C++ 3rd edition Library Introduction to the Standard Template: Introduction to the Standard Template Library Programming Language C++ 3rd edition The: The Programming Language C++ 3rd edition Standard Template Library Introduction to the: Introduction to the Standard Template Library Template Library Introduction to the Standard: Introduction to the Standard Template Library The Design and Evolution of C++: The Design and Evolution of C++ 35 The Programming Language C++ 3rd edition: The Programming Language C++ 3rd edition and Evolution of C++ The Design: The Design and Evolution of C++ edition The Programming Language C++ 3rd: The Programming Language C++ 3rd edition of C++ The Design and Evolution: The Design and Evolution of C++ the Standard Template Library Introduction to: Introduction to the Standard Template Library to the Standard Template Library Introduction: Introduction to the Standard Template Library 36

Assignment 4 (Due 8 April 2001) Let (x i, y i ) be a sequence of pairs of numbers. The regression coefficients are the numbers β0 and β1 such that the linear equiation is the best fit to the data points. The formula are as follows: n β = β 1 0 = y = β + 1x 0 β n n n xi yi xi yi i= 1 i = 1 i= 1 n n 2 2 n xi x i= 1 i= 1 n n yi β1 xi i= 1 i= 1 n 37 Write a program to compute β0 and β1 using the iterators, containers and algorithms of the standard library and function objects either from the standard library or ones that you define. The algorithm accumulate is defined in the header file <numeric> will compute the sum. Input should be from the standard input and consists of a sequence of pairs terminated by end-of-file. (To test your program you may either pipe a file into your program in MS-DOS mode, or manually input the numbers followed by any non-numeric.) Your program should contain no loops. The following is an example of a program that computes the mean and standard deviation of a sequence of numbers: 38

// This program computes the mean and standard deviation // of a sequence of float values entered from standard input. #include <iostream> #include <iterator> #include <algorithm> #include <numeric> #include <vector> #include <math.h> using std::istream; using std::istream_iterator; using std::cin; using std::cout; using std::endl; using std::cerr; using std::copy; using std::back_inserter; using std::accumulate; using std::vector; class AddDiffSquared public: AddDiffSquared(float mean) : m(mean) double operator()(double s, float x) return (s + (x - m)*(x - m)); private: float m; ; 39 int main() istream_iterator<float> in(cin); istream_iterator<float> eos; vector<float> x; copy (in, eos, back_inserter(x)); double sum = accumulate(x.begin(), x.end(), 0.0); float mean = sum/x.size(); double sumdiffsq = accumulate(x.begin(), x.end(), 0.0, AddDiffSquared(mean)); float stdev = sqrt(sumdiffsq/(x.size()-1)); cout << "Mean: " << mean << " Stdev: " << stdev << endl; return 0; 40