The function find. Template function find

Size: px
Start display at page:

Download "The function find. Template function find"

Transcription

1 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

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

3 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

4 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

5 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

6 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

7 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 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

8 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

9 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

10 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

11 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

12 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 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

13 // 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

14 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

15 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

16 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

17 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

18 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

19 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

20 // 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

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

Input file: Fundamentals of Software Engineering Applicators, Manipulators, and Function Objects An introduction to the Standard Template Library APPENDIX 2. Input file: Fundamentals of Software Engineering Applicators, Manipulators, and Function Objects An introduction to the Standard Template Library //Sample input and output of the KWIC program

More information

The Standard Template Library. An introduction

The Standard Template Library. An introduction 1 The Standard Template Library An introduction 2 Standard Template Library (STL) Objective: Reuse common code Common constructs: Generic containers and algorithms STL Part of the C++ Standard Library

More information

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

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI

More information

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

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

pointers & references

pointers & references pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using

More information

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

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides. Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information

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

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

STL: C++ Standard Library

STL: C++ Standard Library STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

CPSC 427a: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 17 November 1, 2011 CPSC 427a, Lecture 17 1/21 CPSC 427a, Lecture 17 2/21 CPSC 427a, Lecture 17 3/21 A bit of history C++ standardization.

More information

Chapter 5. The Standard Template Library.

Chapter 5. The Standard Template Library. Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,

More information

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

Module 9. Templates & STL

Module 9. Templates & STL Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions

More information

Object oriented programming

Object oriented programming Exercises 6 Version 1.0, 21 March, 2017 Table of Contents 1. Operators overloading....................................................... 1 1.1. Example 1..............................................................

More information

C++ Standard Template Library

C++ Standard Template Library C++ Standard Template Library CSE 333 Summer 2018 Instructor: Hal Perkins Teaching Assistants: Renshu Gu William Kim Soumya Vasisht C++ s Standard Library C++ s Standard Library consists of four major

More information

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

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors Announcements CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors HW 1 is available on-line through the website (on the Calendar ). Be sure to read through this information as you start

More information

Lecture-5. STL Containers & Iterators

Lecture-5. STL Containers & Iterators Lecture-5 STL Containers & Iterators Containers as a form of Aggregation Fixed aggregation An object is composed of a fixed set of component objects Variable aggregation An object is composed of a variable

More information

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know

More information

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

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 2 Yusuf Pisan Compiled helloworld yet? Overview C++ fundamentals Assignment-1 CSS Linux Cluster - submitting assignment Call by Value,

More information

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

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each). A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

CS197c: Programming in C++

CS197c: Programming in C++ CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website

More information

Function Templates. Consider the following function:

Function Templates. Consider the following function: Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But

More information

Programming with Haiku

Programming with Haiku Programming with Haiku Lesson 5 Written by DarkWyrm All material 2010 DarkWyrm Let's take some time to put together all of the different bits of code that we've been learning about. Since the first lesson,

More information

Lecture 2. Binary Trees & Implementations. Yusuf Pisan

Lecture 2. Binary Trees & Implementations. Yusuf Pisan CSS 343 Data Structures, Algorithms, and Discrete Math II Lecture 2 Binary Trees & Implementations Yusuf Pisan Overview 1. Huffman Coding and Arithmetic Expressions 2. 342 Topics a. Pointers & References

More information

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

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers part 9 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Functors and Parameterizing STL Functors, Lambdas,

More information

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

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

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

Review: C++ Basic Concepts. Dr. Yingwu Zhu Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Working with Batches of Data

Working with Batches of Data Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Abstract So far we looked at simple read a string print a string problems. Now we will look at more complex problems

More information

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

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

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

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors Announcements CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors HW 1 is available on-line through the website (on the Calendar ). Be sure to read through this information as you start

More information

Strings and Stream I/O

Strings and Stream I/O Strings and Stream I/O C Strings In addition to the string class, C++ also supports old-style C strings In C, strings are stored as null-terminated character arrays str1 char * str1 = "What is your name?

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

MODULE 35 --THE STL-- ALGORITHM PART III

MODULE 35 --THE STL-- ALGORITHM PART III MODULE 35 --THE STL-- ALGORITHM PART III My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation example is given at the end of this

More information

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

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11 Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information

Comp151. Generic Programming: Container Classes

Comp151. Generic Programming: Container Classes Comp151 Generic Programming: Container Classes Container Classes Container classes are a typical use for class templates, since we need container classes for objects of many different types, and the types

More information

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor Operator overloading

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester

More information

Computational Physics

Computational Physics Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

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

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2 TEMPLATES Today This lecture looks at techniques for generic programming: Generic pointers Templates The standard template library Thebestreferenceis: http://www.cppreference.com/index.html andyoucanalsoconsultchapters6amd7inthetextbook.

More information

Set Implementation Version 1

Set Implementation Version 1 Introduction to System Programming 234122 Set Implementation Version 1 Masha Nikolski, CS Department, Technion 1 // Version 1.0 2 // Header file for set class. 3 // In this implementation set is a container

More information

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

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++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

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

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin Permission is granted to copy and distribute freely, for any purpose, provided the copyright notice above is

More information

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

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions 1. You are given a map that associates strings with lists of strings. The definition is: map words; Write

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.

More information

Programming in C++ using STL. Rex Jaeschke

Programming in C++ using STL. Rex Jaeschke Programming in C++ using STL Rex Jaeschke Programming in C++ using STL 1997, 1999, 2002, 2007, 2009 Rex Jaeschke. All rights reserved. Edition: 2.0 All rights reserved. No part of this publication may

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

More information

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

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const. The user. Advanced C++ For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 #define private public #define protected public #define class struct Source: Lutz

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

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

STL. Zoltán Porkoláb: C++11/14 1 STL Generic programming An example inserters, iterator-adapters, functors Efficiency Memory consuption characteristics Std::array Forward_list Unordered containers in C++11 Zoltán Porkoláb: C++11/14 1

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

Standard Library Reference

Standard Library Reference Standard Library Reference This reference shows the most useful classes and functions in the standard library. Note that the syntax [start, end) refers to a half-open iterator range from start to end,

More information

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

Outline. Function calls and results Returning objects by value. return value optimization (RVO) Call by reference or by value? Outline EDAF50 C++ Programming 6... 1 Function calls 2 Sven Gestegård Robertz Computer Science, LTH 2018 3 Standard library algorithms Insert iterators 4 Iterators Different kinds of iterators stream iterators

More information

CS 7B - Spring Final Exam

CS 7B - Spring Final Exam CS 7B - Spring 2018 - Final Exam Write your responses to following questions on this paper, or attach extra, as needed. sentences where appropriate and write out code using proper style and syntax. 1.

More information

EAS 230 Fall 2002 Section B

EAS 230 Fall 2002 Section B EAS 230 Fall 2002 Section B Exam #2 Name: Person Number: Instructions: ƒ Total points are 100, distributed as shown by [ ]. ƒ Duration of the Exam is 50 minutes. I ) State whether True or False [25] Indicate

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

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

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it? Review Describe pass-by-value and pass-by-reference Why do we use pass-by-reference? What does the term calling object refer to? What is a const member function? What is a const object? How do we initialize

More information

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

Use the dot operator to access a member of a specific object. Lab 16 Class A class is a data type that can contain several parts, which are called members. There are two types of members, data member and functions. An object is an instance of a class, and each object

More information

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

Standard Library. Lecture 27. Containers. STL Containers. Standard Library Standard Library Lecture 27 Containers (templates) Streams (I/O facilities) Standard Library Portable, type-safe, efficient Try to use as much as possible Heavy use of templates Streams: #include

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

SETS AND MAPS. Chapter 9

SETS AND MAPS. Chapter 9 SETS AND MAPS Chapter 9 The set Functions Required methods: testing set membership (find) testing for an empty set (empty) determining set size (size) creating an iterator over the set (begin, end) adding

More information

Generic Programming in C++: A modest example

Generic Programming in C++: A modest example Generic Programming in C++: A modest example Marshall Clow Qualcomm Technologies, Inc. mclow@qti.qualcomm.com marshall@idio.com http://cplusplusmusings.wordpress.com Twitter: @mclow Problem Definition

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

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

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 4 (Based on Paul Kube course materials) Lecture 4 Binary search trees Toward a binary search tree implementation using C++ templates Reading: Weiss Ch 4, sections

More information

CS11 Advanced C++ Fall Lecture 1

CS11 Advanced C++ Fall Lecture 1 CS11 Advanced C++ Fall 2006-2007 Lecture 1 Welcome! ~8 lectures Slides are posted on CS11 website http://www.cs.caltech.edu/courses/cs11 ~6 lab assignments More involved labs 2-3 week project at end CS

More information

Major Language Changes, pt. 1

Major Language Changes, pt. 1 C++0x What is C++0x? Updated version of C++ language. Addresses unresolved problems in C++03. Almost completely backwards compatible. Greatly increases expressiveness (and complexity!) of language. Greatly

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 9, 2016 Outline Outline 1 Chapter 9: C++ Classes Outline Chapter 9: C++ Classes 1 Chapter 9: C++ Classes Class Syntax

More information

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

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; }; struct Buffer { Buffer(int s) { buf = new char[s]; ~Buffer() { delete [] buf; char *buf; ; struct FBuffer : public Buffer { FBuffer(int s) : Buffer(s) { f = fopen("file", "w"); ~FBuffer() { fclose(f);

More information

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

CS193D Handout 12 Winter 2005/2006 January 30, 2006 Introduction to Templates and The STL CS193D Handout 12 Winter 2005/2006 January 30, 2006 Introduction to Templates and The STL See also: Chapter 4 (89-100), Chapter 11 (279-281), and Chapter 21 // GameBoard.h class GameBoard { public: //

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

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

CSCI-1200 Data Structures Fall 2009 Lecture 20 Hash Tables, Part II Review from Lecture 19 CSCI-1200 Data Structures Fall 2009 Lecture 20 Hash Tables, Part II Operators as non-member functions, as member functions, and as friend functions. A hash table is a table implementation

More information

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

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

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

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

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

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine Homework 5 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 13, 2013 Question 1 Consider the following Java definition of a mutable string class. class MutableString private char[] chars

More information

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

File I/O Christian Schumacher, Info1 D-MAVT 2013 File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential

More information

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

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit. C++ Basics January 19, 2012 Brian A. Malloy Slide 1 of 24 1. Many find Deitel quintessentially readable; most find Stroustrup inscrutable and overbearing: Slide 2 of 24 1.1. Meyers Texts Two excellent

More information

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

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

Computer Science II Lecture 2 Strings, Vectors and Recursion

Computer Science II Lecture 2 Strings, Vectors and Recursion 1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed

More information

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

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what

More information

Summary of basic C++-commands

Summary of basic C++-commands Summary of basic C++-commands K. Vollmayr-Lee, O. Ippisch April 13, 2010 1 Compiling To compile a C++-program, you can use either g++ or c++. g++ -o executable_filename.out sourcefilename.cc c++ -o executable_filename.out

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

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

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

PENN STATE UNIVERSITY Department of Economics

PENN STATE UNIVERSITY Department of Economics PENN STATE UNIVERSITY Department of Economics Econ 597D Sec 001 Computational Economics Gallant Sample Midterm Exam Questions Fall 2015 In class on Oct 20, 2015 1. Write a C++ program and a makefile to

More information