Operator Overloading

Similar documents
Operator Overloading

Encapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

Unit Testing. Contents. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

Unit Testing. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

The Structure of a C++ Program

Defensive Programming

Common Modifications of Class Members

Common Modifications of Class Members

Common Modifications of Class Members

Patterns: Working with Arrays

The Structure of a C++ Program

Linked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 4

Linked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 3

III. Classes (Chap. 3)

Computer Programming with C++ (21)

CS 1337 Computer Science II Page 1

I/O Streams and Standard I/O Devices (cont d.)

Operator Overloading in C++ Systems Programming

Due Date: See Blackboard

G52CPP C++ Programming Lecture 17

A Deeper Look at Classes

CSI33 Data Structures

Chapter 10 - Notes Applications of Arrays

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

CSCE 110 PROGRAMMING FUNDAMENTALS

Inheritance and Polymorphism

Getting started with C++ (Part 2)

EECE.3220: Data Structures Spring 2017

Classes: A Deeper Look, Part 2

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

CS3157: Advanced Programming. Outline

Variables. Data Types.

A C++ Class Designer s Checklist

Lab 2: ADT Design & Implementation

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

Introduction to C++ (Extensions to C)

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Lecture 7. Log into Linux New documents posted to course webpage

CS2141 Software Development using C/C++ Stream I/O

pointers & references

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

COMP322 - Introduction to C++

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Chapter 18 - C++ Operator Overloading

Assignment 2 Solution

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

2. It is possible for a structure variable to be a member of another structure variable.

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

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

REVIEW. The C++ Programming Language. CS 151 Review #2

Object Oriented Programming COP3330 / CGS5409

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

10/23/02 21:20:33 IO_Examples

Practice Problems CS2620 Advanced Programming, Spring 2003

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

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

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

Programming. C++ Basics

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

Chapter 2 - Control Structures

2 nd Week Lecture Notes

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

G52CPP C++ Programming Lecture 18

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

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

Software Design Abstract Data Types

Due Date: See Blackboard

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

OBJECT ORIENTED PROGRAMMING USING C++

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

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

Recursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

C++ Quick Guide. Advertisements

typedef Labeling<unsigned char,short> LabelingBS; typedef Labeling<unsigned char,short>::regioninfo RegionInfoBS;

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

What we will learn about this week:

C C C C++ 2 ( ) C C++ 4 C C

C++_ MARKS 40 MIN

C++ Input/Output: Streams

Lecture 5 Files and Streams

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

Pointers and References

COMP322 - Introduction to C++

Fast Introduction to Object Oriented Programming and C++

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

C++ for Python Programmers

Fundamentals of Programming CS-110. Lecture 2

Transcription:

Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions...................................................... 2 2 I/O Operators 4 3 Comparison Operators 38 3.1 Equality Operators......................................................... 49 3.2 Less-Than Operators........................................................ 52 1

1 Operators Lots of Operators In C++, almost every operator in the language can be declared for our own classes. In most programming languages, we can write things like x+y or x<y only if x and y are integers, floating point numbers, or some other pre-defined type in the language. In C++, we can add these operators to any class we design, if we feel that they are appropriate. These include + - * / & < > <= >= = ==!= ++ - -> += -= *= /= For example, the std::string class declares these for strings: + < > <= >= = ==!= +=............................................. 1.1 Operators are Functions Operators are Functions Each operator is actually a shorthand for a function named operator? where the? is replaced by the actual operator symbol. The function takes the same number and type of parameters as does the operator The compiler translates the infix expressions into the equivalent function calls............................................. Examples: operators as functions If you write a + b*(-c), that s actually just a shorthand for operator +(a, operator * ( b, operator (c ) ) ) CS250 2

and if you write testvalue = ( x <= y ) ; that s actually a shorthand for operator =( testvalue, operator <=(x, y ) ;............................................. Declaring Operators Understanding that shorthand, we can declare our own operators by giving the appropriate operator function name: class BidCollection. void addintimeorder (const Bid& value); // Adds this bid into a position such that // all bids are ordered by the time the bid was placed //Pre: getsize() < getmaxsize() void operator+= (const Bid& value) addintimeorder(value);. Then bids. addintimeorder (b ) ; and bids += b ; would do the same thing............................................. CS250 3

Keep it Natural It s easy to abuse operator overloading and simply make things confusing. E.g., Don t use operator+ unless your class really does something "addition-like" * string concatenation............................................. Most Commonly Overloaded Operators There are, however, 3 groups of operators that are very commonly overloaded I/O operators << >> Comparison operators < == The assignment operator =............................................. 2 I/O Operators I/O Operators Perhaps the most commonly declared operators We have already seen that there is good reason for every class to provide an output function. But the most common form for this is the operator <<............................................. CS250 4

Providing the Output Operator For example, our Bid class already looks like: class Bid. public : Bid ( std : : string bidder, double amt, std : : s t r i n g item, Time placedat ) ; Bid ( ) ; / / Access to attribute std : : string getbidder ( ) const return biddername ; double getamount ( ) const return amount ; std : : string getitem ( ) const return itemname ; Time gettimeplacedat ( ) const return bidplacedat ; / / Print a bid void print ( std : : ostream& out ) const ; ; All we need to do is add: inline std : : ostream& operator<< ( std : : ostream& out, const Bid& b) b. print ( out ) ; return out ;............................................. Lots of Ops The whole program, with output operators: The Bid ADT: CS250 5

#ifndef BIDS_H #define BIDS_H #include <iostream> #include <string> #include "time.h" // // Bids Received During Auction // class Bid std::string biddername; double amount; std::string itemname; Time bidplacedat; public: Bid (std::string bidder, double amt, std::string item, Time placedat); Bid(); // Access to attribute std::string getbidder() const return biddername; double getamount() const return amount; std::string getitem() const return itemname; Time gettimeplacedat() const return bidplacedat; CS250 6

// Print a bid void print (std::ostream& out) const; ; inline std::ostream& operator<< (std::ostream& out, const Bid& b) b.print(out); return out; #endif and #include <string> #include <fstream> using namespace std; // // Bids Received During Auction // #include "bids.h" Bid::Bid (std::string bidder, double amt, CS250 7

std::string item, Time placedat) : biddername(bidder), amount(amt), itemname(item), bidplacedat(placedat) Bid::Bid () : amount(0.0) // Print a bid void Bid::print (std::ostream& out) const out << "[" << biddername << " " << amount << " " << itemname << " " << bidplacedat << "]"; The Bidder ADT: #ifndef BIDDERS_H #define BIDDERS_H #include <iostream> #include <string> // // Bidders Registered for auction // CS250 8

class Bidder // describes someone registered to participate in an auction std::string name; double balance; public: Bidder(); Bidder (std::string thename, double thebalance); // Access to attributes std::string getname() const return name; double getbalance() const return balance; void setbalance (double newbal) balance = newbal; // print a bidder void print (std::ostream& out) const; ; inline std::ostream& operator<< (std::ostream& out, const Bidder& b) b.print(out); return out; #endif CS250 9

and #include <string> #include <fstream> #include <iostream> // // Bidders Registered for auction // #include "bidders.h" using namespace std; Bidder::Bidder() name = ""; balance = 0.0; Bidder::Bidder (std::string thename, double thebalance) name = thename; balance = thebalance; // print a bidder void Bidder::print (std::ostream& out) const CS250 10

out << "[" << name << " " << balance << "]"; The Item ADT: #ifndef ITEMS_H #define ITEMS_H #include <iostream> #include <string> #include "time.h" // // Items up for auction // class Item std::string name; double reservedprice; Time auctionendsat; public: Item(); Item (std::string itemname, double reserve, Time auctionend); // Access to attribute std::string getname() const return name; CS250 11

double getreservedprice() const return reservedprice; Time getauctionendtime() const return auctionendsat; * Read one item from the indicated file void read (std::istream& in); // Print an item void print (std::ostream& out) const; ; inline std::ostream& operator<< (std::ostream& out, const Item& b) b.print(out); return out; #endif and #include <iostream> #include <fstream> #include "items.h" // CS250 12

// Items up for auction // using namespace std; Item::Item() : reservedprice(0.0) Item::Item (std::string itemname, double reserve, Time auctionend) : name(itemname), reservedprice(reserve), auctionendsat(auctionend) * Read one item from the indicated file void Item::read (istream& in) in >> reservedprice; auctionendsat.read (in); // Reading the item name. char c; in >> c; // Skips blanks and reads first character of the name string line; CS250 13

getline (in, line); // Read the rest of the line name = string(1,c) + line; // print a bidder void Item::print (std::ostream& out) const out << "[" << name << " " << reservedprice << " " << auctionendsat << "]"; The Time ADT: #ifndef TIMES_H #define TIMES_H #include <iostream> * Times in this program are represented by three integers: H, M, & S, representing * the hours, minutes, and seconds, respecitvely. struct Time // Create time objects Time(); // midnight Time (int h, int m, int s); // Access to attributes CS250 14

int gethours() const; int getminutes() const; int getseconds() const; // Calculations with time void add (Time delta); Time difference (Time fromtime); * Read a time (in the format HH:MM:SS) after skipping any * prior whitepace. void read (std::istream& in); * Print a time in the format HH:MM:SS (two digits each) void print (std::ostream& out) const; * Compare two times. Return true iff time1 is earlier than or equal to * time2 bool nolaterthan(const Time& time2); * Compare two times. Return true iff time1 is equal to * time2 * CS250 15

bool equalto(const Time& time2); // From here on is hidden int secondssincemidnight; ; inline std::ostream& operator<< (std::ostream& out, const Time& t) t.print(out); return out; inline std::istream& operator>> (std::istream& in, Time& t) t.read(in); return in; #endif // TIMES_H and #include "time.h" #include <iomanip> using namespace std; CS250 16

* Times in this program are represented by three integers: H, M, & S, representing * the hours, minutes, and seconds, respecitvely. // Create time objects Time::Time() // midnight secondssincemidnight = 0; Time::Time (int h, int m, int s) secondssincemidnight = s + 60 * m + 3600*h; // Access to attributes int Time::getHours() const return secondssincemidnight / 3600; int Time::getMinutes() const return (secondssincemidnight % 3600) / 60; int Time::getSeconds() const CS250 17

return secondssincemidnight % 60; // Calculations with time void Time::add (Time delta) secondssincemidnight += delta.secondssincemidnight; Time Time::difference (Time fromtime) Time diff; diff.secondssincemidnight = secondssincemidnight - fromtime.secondssincemidnight; * Read a time (in the format HH:MM:SS) after skipping any * prior whitepace. void Time::read (std::istream& in) char c; int hours, minutes, seconds; in >> hours >> c >> minutes >> c >> seconds; Time t (hours, minutes, seconds); secondssincemidnight = t.secondssincemidnight; CS250 18

* Print a time in the format HH:MM:SS (two digits each) void Time::print (std::ostream& out) const out << setfill( 0 ) << setw(2) << gethours() << : << setfill( 0 ) << setw(2) << getminutes() << : << setfill( 0 ) << setw(2) << getseconds(); * Compare two times. Return true iff time1 is earlier than or equal to * time2 bool Time::noLaterThan(const Time& time2) return secondssincemidnight <= time2.secondssincemidnight; * Compare two times. Return true iff time1 is equal to * time2 * bool Time::equalTo(const Time& time2) CS250 19

return secondssincemidnight == time2.secondssincemidnight; The BidCollection ADT: #ifndef BIDCOLLECTION_H #define BIDCOLLECTION_H #include "bids.h" #include <iostream> class BidCollection int MaxSize; int size; Bid* elements; // array of bids public: * Create a collection capable of holding the indicated number of bids BidCollection (int MaxBids = 1000); ~BidCollection (); // Access to attributes int getmaxsize() const return MaxSize; CS250 20

int getsize() const return size; // Access to individual elements const Bid& get(int index) const return elements[index]; // Collection operations void addintimeorder (const Bid& value); // Adds this bid into a position such that // all bids are ordered by the time the bid was placed //Pre: getsize() < getmaxsize() void remove (int index); // Remove the bid at the indicated position //Pre: 0 <= index < getsize() * Read all bids from the indicated file void readbids (std::string filename); // Print the collection CS250 21

void print (std::ostream& out) const; ; inline std::ostream& operator<< (std::ostream& out, const BidCollection& b) b.print(out); return out; #endif and #include "bidcollection.h" #include "arrayutils.h" #include <fstream> using namespace std; * Create a collection capable of holding the indicated number of bids BidCollection::BidCollection (int MaxBids) : MaxSize(MaxBids), size(0) elements = new Bid [MaxSize]; CS250 22

BidCollection::~BidCollection () delete [] elements; // Collection operations void BidCollection::addInTimeOrder (const Bid& value) // Adds this bid into a position such that // all bids are ordered by the time the bid was placed //Pre: getsize() < getmaxsize() // Make room for the insertion int tobemoved = size - 1; while (tobemoved >= 0 && value.gettimeplacedat().nolaterthan(elements[tobemoved].gettimeplacedat())) elements[tobemoved+1] = elements[tobemoved]; --tobemoved; // Insert the new value elements[tobemoved+1] = value; ++size; void BidCollection::remove (int index) // Remove the bid at the indicated position //Pre: 0 <= index < getsize() CS250 23

removeelement (elements, size, index); * Read all bids from the indicated file void BidCollection::readBids (std::string filename) size = 0; ifstream in (filename.c_str()); int nbids; in >> nbids; for (int i = 0; i < nbids; ++i) char c; string biddername; double amount; in >> biddername >> amount; Time bidplacedat; bidplacedat.read (in); string word, line; in >> word; // First word of itemname getline (in, line); // rest of item name string itemname = word + line; addintimeorder (Bid (biddername, amount, itemname, bidplacedat)); CS250 24

// Print the collection void BidCollection::print (std::ostream& out) const out << size << "/" << MaxSize << ""; for (int i = 0; i < size; ++i) out << " "; elements[i].print (out); out << "n"; out << ""; The BidderCollection ADT: #ifndef BIDDERCOLLECTION_H #define BIDDERCOLLECTION_H #include "bidders.h" #include <iostream> // // Bidders Registered for auction // class BidderCollection CS250 25

int MaxSize; int size; Bidder* elements; // array of items public: * Create a collection capable of holding the indicated number of items BidderCollection (int MaxBidders = 1000); ~BidderCollection (); // Access to attributes int getmaxsize() const return MaxSize; int getsize() const return size; // Access to individual elements Bidder& get(int index) return elements[index]; // Collection operations CS250 26

int add (const Bidder& value); // Adds this bidder to the collection at an unspecified position. // Returns the position where added. //Pre: getsize() < getmaxsize() void remove (int index); // Remove the item at the indicated position //Pre: 0 <= index < getsize() int findbidder (std::string name) const; // Returns the position where a bidde mathcing the given // name can be found, or getsize() if no bidder with that name exists. * Read all items from the indicated file void readbidders (std::string filename); // Print the collection void print (std::ostream& out) const; ; inline std::ostream& operator<< (std::ostream& out, const BidderCollection& b) b.print(out); CS250 27

return out; #endif and #include <iostream> #include "arrayutils.h" #include <fstream> #include "biddercollection.h" using namespace std; * Create a collection capable of holding the indicated number of items BidderCollection::BidderCollection (int MaxBidders) : MaxSize(MaxBidders), size(0) elements = new Bidder [MaxSize]; BidderCollection::~BidderCollection () delete [] elements; CS250 28

// Collection operations int BidderCollection::add (const Bidder& value) // Adds this bidder //Pre: getsize() < getmaxsize() addtoend (elements, size, value); return size - 1; void BidderCollection::remove (int index) // Remove the bidder at the indicated position //Pre: 0 <= index < getsize() removeelement (elements, size, index); * Read all bidders from the indicated file void BidderCollection::readBidders (std::string filename) CS250 29

size = 0; ifstream in (filename.c_str()); int nbidders; in >> nbidders; for (int i = 0; i < nbidders && i < MaxSize; ++i) string nme; double bal; in >> nme >> bal; Bidder bidder (nme, bal);; add (bidder); * Find the index of the bidder with the given name. If no such bidder exists, * return nbidders. int BidderCollection::findBidder (std::string name) const int found = size; for (int i = 0; i < size && found == size; ++i) if (name == elements[i].getname()) found = i; return found; CS250 30

// Print the collection void BidderCollection::print (std::ostream& out) const out << size << "/" << MaxSize << ""; for (int i = 0; i < size; ++i) out << " "; elements[i].print (out); out << "n"; out << ""; The ItemCollection ADT: #ifndef ITEMCOLLECTION_H #define ITEMCOLLECTION_H #include "items.h" #include <iostream> class ItemCollection int MaxSize; int size; Item* elements; // array of items public: * Create a collection capable of holding the indicated number of items CS250 31

ItemCollection (int MaxItems = 1000); ~ItemCollection (); // Access to attributes int getmaxsize() const return MaxSize; int getsize() const return size; // Access to individual elements const Item& get(int index) const return elements[index]; // Collection operations void addintimeorder (const Item& value); // Adds this item into a position such that // all items are ordered by the time at which the auction for the // item ends. //Pre: getsize() < getmaxsize() CS250 32

void remove (int index); // Remove the item at the indicated position //Pre: 0 <= index < getsize() * Read all items from the indicated file void readitems (std::string filename); // Print the collection void print (std::ostream& out) const; ; inline std::ostream& operator<< (std::ostream& out, const ItemCollection& b) b.print(out); return out; #endif and #include <iostream> #include "arrayutils.h" #include <fstream> CS250 33

#include "itemcollection.h" // // Items up for auction // using namespace std; * Create a collection capable of holding the indicated number of items ItemCollection::ItemCollection (int MaxItems) : MaxSize(MaxItems), size(0) elements = new Item [MaxSize]; ItemCollection::~ItemCollection () delete [] elements; // Collection operations void ItemCollection::addInTimeOrder (const Item& value) // Adds this item into a position such that CS250 34

// all items are ordered by the time the item auction ends //Pre: getsize() < getmaxsize() // Make room for the insertion int tobemoved = size - 1; while (tobemoved >= 0 && value.getauctionendtime().nolaterthan(elements[tobemoved].getauctionendtime())) elements[tobemoved+1] = elements[tobemoved]; --tobemoved; // Insert the new value elements[tobemoved+1] = value; ++size; void ItemCollection::remove (int index) // Remove the item at the indicated position //Pre: 0 <= index < getsize() removeelement (elements, size, index); * Read all items from the indicated file void ItemCollection::readItems (std::string filename) size = 0; CS250 35

ifstream in (filename.c_str()); int nitems; in >> nitems; for (int i = 0; i < nitems; ++i) Item item; item.read (in); addintimeorder (item); // Print the collection void ItemCollection::print (std::ostream& out) const out << size << "/" << MaxSize << ""; for (int i = 0; i < size; ++i) out << " "; elements[i].print (out); out << "n"; out << "";............................................. Using the Output Op Note how much cleaner the debugging output statements look. Instead of i f ( bid. getamount ( ) <= bidder. getbalance ( ) ) CS250 36

highestbidsofar = bid. getamount ( ) ; winningbiddersofar = bid. getbidder ( ) ; cerr << " Best bid so far i s " ; bid. print ( cerr ) ; cerr << " from " ; bidder. print ( cerr ) ; cerr << endl ;............................................. Debugging With Output Op we now can write i f ( bid. getamount ( ) <= bidder. getbalance ( ) ) highestbidsofar = bid. getamount ( ) ; winningbiddersofar = bid. getbidder ( ) ; cerr << " Best bid so far i s " << bid << " from " << bidder << endl ;............................................. Return Values The << operator must return the stream it is applied to. That s why we can write things like cout << a << b; The compiler treats this as ( cout << a ) << b ; CS250 37

What is the << b applied to? To the value returned by (cout << a)! You can also view this as operator <<(operator <<(cout, a ), b)............................................. Fine Points These are not member functions, so they cannot access private data directly You can get around this by using friend declarations described in the text. Programming input operators is less common, but very similar to output operators.............................................. 3 Comparison Operators Comparison Operators Almost every class should provide == and < operators. Many data structures and functions in the standard library assume these are available. So do some of the ones we have developed, e.g., in #ifndef ARRAYUTILS_H #define ARRAYUTILS_H CS250 38

// Add to the end // - Assumes that we have a separate integer (size) indicating how // many elements are in the array // - and that the "true" size of the array is at least one larger // than the current value of that counter template <typename T> void addtoend (T* array, int& size, T value) array[size] = value; ++size; // Add value into array[index], shifting all elements already in positions // index..size-1 up one, to make room. // - Assumes that we have a separate integer (size) indicating how // many elements are in the array // - and that the "true" size of the array is at least one larger // than the current value of that counter template <typename T> void addelement (T* array, int& size, int index, T value) // Make room for the insertion int tobemoved = size - 1; while (tobemoved >= index) array[tobemoved+1] = array[tobemoved]; --tobemoved; CS250 39

// Insert the new value array[index] = value; ++size; // Assume the elements of the array are already in order // Find the position where value could be added to keep // everything in order, and insert it there. // Return the position where it was inserted // - Assumes that we have a separate integer (size) indicating how // many elements are in the array // - and that the "true" size of the array is at least one larger // than the current value of that counter template <typename T> int addinorder (T* array, int& size, T value) // Make room for the insertion int tobemoved = size - 1; while (tobemoved >= 0 && value < array[tobemoved]) array[tobemoved+1] = array[tobemoved]; --tobemoved; // Insert the new value array[tobemoved+1] = value; ++size; return tobemoved+1; CS250 40

// Search an array for a given value, returning the index where // found or -1 if not found. template <typename T> int seqsearch(const T list[], int listlength, T searchitem) int loc; for (loc = 0; loc < listlength; loc++) if (list[loc] == searchitem) return loc; return -1; // Search an ordered array for a given value, returning the index where // found or -1 if not found. template <typename T> int seqorderedsearch(const T list[], int listlength, T searchitem) int loc = 0; while (loc < listlength && list[loc] < searchitem) ++loc; if (loc < listlength && list[loc] == searchitem) return loc; else return -1; CS250 41

// Removes an element from the indicated position in the array, moving // all elements in higher positions down one to fill in the gap. template <typename T> void removeelement (T* array, int& size, int index) int tobemoved = index + 1; while (tobemoved < size) array[tobemoved] = array[tobemoved+1]; ++tobemoved; --size; // Search an ordered array for a given value, returning the index where // found or -1 if not found. template <typename T> int binarysearch(const T list[], int listlength, T searchitem) int first = 0; int last = listlength - 1; int mid; bool found = false; while (first <= last &&!found) mid = (first + last) / 2; CS250 42

if (list[mid] == searchitem) found = true; else if (searchitem < list[mid]) last = mid - 1; else first = mid + 1; if (found) return mid; else return -1; #endif............................................. Comparison Operators for Time We declare the comparison ops the same way we do other operator functions Time is a simple case, since it has only one data member #ifndef TIMES_H #define TIMES_H CS250 43

#include <iostream> * Times in this program are represented by three integers: H, M, & S, representing * the hours, minutes, and seconds, respecitvely. class Time public: // Create time objects Time(); // midnight Time (int h, int m, int s); // Access to attributes int gethours() const; int getminutes() const; int getseconds() const; // Calculations with time void add (Time delta); Time difference (Time fromtime); * Read a time (in the format HH:MM:SS) after skipping any * prior whitepace. void read (std::istream& in); CS250 44

* Print a time in the format HH:MM:SS (two digits each) void print (std::ostream& out) const; // Comparison operators bool operator== (const Time&) const; bool operator< (const Time&) const; private: // From here on is hidden int secondssincemidnight; ; inline std::ostream& operator<< (std::ostream& out, const Time& t) t.print(out); return out; inline bool operator!= (const Time& t1, const Time& t2) return!(t1 == t2); CS250 45

inline bool operator> (const Time& t1, const Time& t2) return t2 < t1; inline bool operator<= (const Time& t1, const Time& t2) return!(t1 > t2); inline bool operator>= (const Time& t1, const Time& t2) return!(t1 < t2); #endif // TIMES_H #include "time.h" #include <iomanip> using namespace std; * Times in this program are represented by three integers: H, M, & S, representing CS250 46

* the hours, minutes, and seconds, respecitvely. // Create time objects Time::Time() // midnight secondssincemidnight = 0; Time::Time (int h, int m, int s) secondssincemidnight = s + 60 * m + 3600*h; // Access to attributes int Time::getHours() const return secondssincemidnight / 3600; int Time::getMinutes() const return (secondssincemidnight % 3600) / 60; int Time::getSeconds() const return secondssincemidnight % 60; CS250 47

// Calculations with time void Time::add (Time delta) secondssincemidnight += delta.secondssincemidnight; Time Time::difference (Time fromtime) Time diff; diff.secondssincemidnight = secondssincemidnight - fromtime.secondssincemidnight; * Read a time (in the format HH:MM:SS) after skipping any * prior whitepace. void Time::read (std::istream& in) char c; int hours, minutes, seconds; in >> hours >> c >> minutes >> c >> seconds; Time t (hours, minutes, seconds); secondssincemidnight = t.secondssincemidnight; CS250 48

* Print a time in the format HH:MM:SS (two digits each) void Time::print (std::ostream& out) const out << setfill( 0 ) << setw(2) << gethours() << : << setfill( 0 ) << setw(2) << getminutes() << : << setfill( 0 ) << setw(2) << getseconds(); // Comparison operators bool Time::operator< (const Time& time2) const return secondssincemidnight < time2.secondssincemidnight; bool Time::operator==(const Time& time2) const return secondssincemidnight == time2.secondssincemidnight;............................................. 3.1 Equality Operators Equality Operators for Compound Data You have to think about what you want == to mean for your ADT. CS250 49

May depend on the application............................................. Common: Compare Every Member For ADTs with multiple data members, we often expect every "significant" data member to match. E.g., class Bid std : : string biddername ; double amount ; std : : s t r i n g itemname ; Time bidplacedat ;. can be compared like this bool Bid : : operator== ( const Bid& b) const return biddername == b. biddername && amount == b. amount && itemname == b. itemname && bidplacedat == b. bidplacedat ;............................................. Highly Variable Data Fields that change frequently may or may not be significant: bool Bidder : : operator== ( const Bidder& b) const return name == b.name; / / ignore balance CS250 50

Two Bidder records describe the same person if the names match, even if their bank balances differ. Some would say that the name is a key that identifies the Bidder,............................................. Equality for ADTs with Arrays bool BidCollection : : operator== ( const BidCollection& bc ) const i f ( s i z e == bc. s i z e ) ❶ for ( int i = 0 ; i < size ; ++ i ) ❷ i f (! ( elements [ i ] == ❸bc. elements [ i ] ) ) return false ; return true ; else return false ; ❶ Do the quick & easy check first (size) ❷ Then insist that each array element must match ❸ Note that this uses the Bid::operator== we developed above I did not compare the MaxSize values because that is not, logically, part of the value of the collection.............................................. CS250 51

3.2 Less-Than Operators < is not always less than What does < mean for compound data structures? Can a bid, for example, be said to be "less than" another bid? Bidders? Items? < is used mainly to put things into a sorted order So think of it as meaning "comes before", not "is smaller than"............................................. Less-than on Compound Data For ADTs with multiple data members, we usually model operator< on lexicographic (alphabetic) order rules. 1. When comparing two strings, we compare the first two characters 2. If they are different, we immediately decide that one string is < than the other. 3. If they are equal, we move on to the next character and repeat steps 2-3 E.g., "abc" < "bbc", "cbc" > "bbc", "abc" < "abd", "abc" > "aba"............................................. Extending Lexicographic Order to Non-Strings Compare members until we find two that are not equal: bool Bid : : operator< ( const Bid& b) const i f ( bidplacedat < b. bidplacedat ) return true ; else i f (b. bidplacedat < bidplacedat ) return false ; CS250 52

i f ( biddername < b. biddername ) return true ; else i f (b. biddername < biddername ) return false ; i f (itemname < b. itemname) return true ; else i f (b. itemname < itemname) return false ; i f (amount < b. amount) return true ; else i f (b. amount < amount) return false ; return false ;............................................. Less-than for ADTs with Arrays We extend the same idea to arrays of data: bool BidCollection : : operator< ( const BidCollection& bc ) const i f ( s i z e == bc. s i z e ) ❶ for ( int i = 0 ; i < size ; ++ i ) ❷ i f ( elements [ i ] < bc. elements [ i ] ) ❸ return true ; else i f ( bc. elements [ i ] < elements [ i ] ) ❸ return false ; CS250 53

/ / e l s e keep going / / Al l of the elements are equal return false ; ❹ else return size < bc. size ; ❶ ❶ Do the quick & easy check first (size) ❷ Then run through the arrays until we find two elements that are not equal (❸) ❹ If all the array elements are equal, then this is not less than the other (they are equal).............................................. Adding Both == and < We often have choices in how to implement these two. They must be consistent. For any two values x and y, exactly one of the following conditions must be true: x == y x < y y > x A good rule of thumb: every data member checked by == should be checked by <, and vice-versa............................................. CS250 54

Why Just Two? Why do we often just provide == and <? It s easy to define the others in terms of these two. #ifndef TIMES_H #define TIMES_H #include <iostream> * Times in this program are represented by three integers: H, M, & S, representing * the hours, minutes, and seconds, respecitvely. class Time public: // Create time objects Time(); // midnight Time (int h, int m, int s); // Access to attributes int gethours() const; int getminutes() const; int getseconds() const; // Calculations with time void add (Time delta); Time difference (Time fromtime); CS250 55

* Read a time (in the format HH:MM:SS) after skipping any * prior whitepace. void read (std::istream& in); * Print a time in the format HH:MM:SS (two digits each) void print (std::ostream& out) const; // Comparison operators bool operator== (const Time&) const; bool operator< (const Time&) const; private: // From here on is hidden int secondssincemidnight; ; inline std::ostream& operator<< (std::ostream& out, const Time& t) t.print(out); return out; CS250 56

inline bool operator!= (const Time& t1, const Time& t2) return!(t1 == t2); inline bool operator> (const Time& t1, const Time& t2) return t2 < t1; inline bool operator<= (const Time& t1, const Time& t2) return!(t1 > t2); inline bool operator>= (const Time& t1, const Time& t2) return!(t1 < t2); #endif // TIMES_H in fact, the C++ std library has function templates that already do this. If your file #includes the header <utility> and has the statement using namespace std : : rel_ops ; then the operators!=, >, <=, and >= will be provided based on your own == and <. CS250 57

............................................. Taking Advantage of the Relational Ops If we make a habit of providing these, we can often use "canned" versions of our algorithms instead of needing to write specialized versions. Compare: #ifndef ARRAYUTILS_H #define ARRAYUTILS_H // Add to the end // - Assumes that we have a separate integer (size) indicating how // many elements are in the array // - and that the "true" size of the array is at least one larger // than the current value of that counter template <typename T> void addtoend (T* array, int& size, T value) array[size] = value; ++size; // Add value into array[index], shifting all elements already in positions // index..size-1 up one, to make room. // - Assumes that we have a separate integer (size) indicating how // many elements are in the array // - and that the "true" size of the array is at least one larger CS250 58

// than the current value of that counter template <typename T> void addelement (T* array, int& size, int index, T value) // Make room for the insertion int tobemoved = size - 1; while (tobemoved >= index) array[tobemoved+1] = array[tobemoved]; --tobemoved; // Insert the new value array[index] = value; ++size; // Assume the elements of the array are already in order // Find the position where value could be added to keep // everything in order, and insert it there. // Return the position where it was inserted // - Assumes that we have a separate integer (size) indicating how // many elements are in the array // - and that the "true" size of the array is at least one larger // than the current value of that counter template <typename T> int addinorder (T* array, int& size, T value) // Make room for the insertion int tobemoved = size - 1; CS250 59

while (tobemoved >= 0 && value < array[tobemoved]) array[tobemoved+1] = array[tobemoved]; --tobemoved; // Insert the new value array[tobemoved+1] = value; ++size; return tobemoved+1; // Search an array for a given value, returning the index where // found or -1 if not found. template <typename T> int seqsearch(const T list[], int listlength, T searchitem) int loc; for (loc = 0; loc < listlength; loc++) if (list[loc] == searchitem) return loc; return -1; // Search an ordered array for a given value, returning the index where // found or -1 if not found. template <typename T> int seqorderedsearch(const T list[], int listlength, T searchitem) CS250 60

int loc = 0; while (loc < listlength && list[loc] < searchitem) ++loc; if (loc < listlength && list[loc] == searchitem) return loc; else return -1; // Removes an element from the indicated position in the array, moving // all elements in higher positions down one to fill in the gap. template <typename T> void removeelement (T* array, int& size, int index) int tobemoved = index + 1; while (tobemoved < size) array[tobemoved] = array[tobemoved+1]; ++tobemoved; --size; // Search an ordered array for a given value, returning the index where // found or -1 if not found. template <typename T> CS250 61

int binarysearch(const T list[], int listlength, T searchitem) int first = 0; int last = listlength - 1; int mid; bool found = false; while (first <= last &&!found) mid = (first + last) / 2; if (list[mid] == searchitem) found = true; else if (searchitem < list[mid]) last = mid - 1; else first = mid + 1; if (found) return mid; else return -1; CS250 62

#endif The customized version for ItemCollection: void ItemCollection::addInTimeOrder (const Item& value) // Adds this item into a position such that // all items are ordered by the time the item auction ends //Pre: getsize() < getmaxsize() // Make room for the insertion int tobemoved = size - 1; while (tobemoved >= 0 && value.getauctionendtime().nolaterthan(elements[tobemoved].getauctionendtime())) elements[tobemoved+1] = elements[tobemoved]; --tobemoved; // Insert the new value elements[tobemoved+1] = value; ++size; But after providing relational ops on Items: void ItemCollection : : addintimeorder ( const Item& value ) / / Adds t h i s item into a position such that / / a l l items are ordered by the time the item auction ends / / Pre : getsize ( ) < getmaxsize ( ) addinorder ( elements, size, value ) ;............................................. CS250 63