Operator Overloading
|
|
- Edwin Holmes
- 5 years ago
- Views:
Transcription
1 Steven Zeil November 4, 2013 Contents 1 Operators Operators are Functions I/O Operators 4 3 Comparison Operators Equality Operators Less-Than Operators
2 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: + < > <= >= = ==!= += 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
3 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
4 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 = 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
5 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
6 #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
7 // 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
8 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
9 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
10 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
11 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
12 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
13 // 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
14 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
15 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
16 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
17 * 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 *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
18 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
19 * 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
20 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
21 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
22 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
23 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
24 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
25 // 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
26 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
27 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
28 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
29 // 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
30 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
31 // 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
32 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
33 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
34 #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
35 // 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
36 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
37 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
38 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 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
39 // 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
40 // 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
41 // 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
42 // 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
43 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
44 #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
45 * 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
46 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
47 * 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 *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
48 // 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
49 * 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; Equality Operators Equality Operators for Compound Data You have to think about what you want == to mean for your ADT. CS250 49
50 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
51 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
52 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
53 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
54 / / 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
55 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
56 * 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
57 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
58 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
59 // 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
60 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
61 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
62 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
63 #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
Operator Overloading
Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions.... 2 2 I/O Operators 4 3 Comparison Operators 6 3.1 Equality Operators....... 11 3.2 Less-Than Operators...... 13 1 1 Operators
More informationEncapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8
Steven Zeil July 17, 2013 Contents 1 Encapsulation 2 1.1 Encapsulation in C++........................................................ 2 2 Classes 4 3 Hiding Attributes 8 4 Inline Functions 11 4.1 How Functions
More informationCopying Data. Contents. Steven J. Zeil. November 13, Destructors 2
Steven J. Zeil November 13, 2013 Contents 1 Destructors 2 2 Copy Constructors 11 2.1 Where Do We Use a Copy Constructor? 12 2.2 Compiler-Generated Copy Constructors............................................
More informationUnit Testing. Contents. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...
Steven Zeil July 22, 2013 Contents 1 Types of Testing 2 2 6 2.1 Scaffolding................. 7 2.1.1 Drivers............... 7 2.1.2 Stubs................ 13 3 Integration Testing 17 1 1 Types of Testing
More informationUnit Testing. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...
Steven Zeil July 22, 2013 Contents 1 Types of Testing 2 2 Unit Testing 4 2.1 Scaffolding............ 4 2.1.1 Drivers.......... 4 2.1.2 Stubs........... 9 3 Integration Testing 12 1 1 Types of Testing Testing
More informationThe Structure of a C++ Program
Steven Zeil May 25, 2013 Contents 1 Separate Compilation 3 1.1 Separate Compilation.......... 4 2 Pre-processing 7 2.1 #include.................. 9 2.2 Other Pre-processing Commands... 14 3 Declarations
More informationDefensive Programming
Steven Zeil July 22, 2013 Contents 1 Common Assumptions 2 2 Documenting Assumptions 2 3 Guarding Assumptions 5 3.1 Guarding Assumptions with Assertions............................... 8 1 Defensive Programming
More informationCommon Modifications of Class Members
Steven Zeil July 13, 2013 Contents 1 Static 2 1.1 Static Data Members...... 2 1.2 Static Function Members... 9 2 const 10 2.1 const Pointers and References 11 2.2 Is your class const-correct?.. 12 1 1
More informationCommon Modifications of Class Members
Steven Zeil July 13, 2013 Contents 1 Static 2 1.1 Static Data Members........... 2 1.2 Static Function Members........ 10 2 const 12 2.1 const Pointers and References..... 13 2.2 Is your class const-correct?.......
More informationCommon Modifications of Class Members
Steven Zeil July 13, 2013 Contents 1 Static 3 1.1 Static Data Members. 3 1.2 Static Function Members.......................... 18 2 const 22 2.1 const Pointers and References....................... 24
More informationPatterns: Working with Arrays
Steven Zeil October 14, 2013 Outline 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates
More informationThe Structure of a C++ Program
Steven Zeil August 31, 2013 Contents 1 Separate Compilation 2 1.1 Separate Compilation.......... 3 2 Pre-processing 5 2.1 #include.................. 7 2.2 Other Pre-processing Commands... 10 3 Declarations
More informationLinked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 4
Steven J. Zeil July 31, 2013 Contents 1 Linked Lists: the Basics 4 1 2 Coding for Linked Lists 8 2.1 Traversing a Linked List............................... 12 2.2 Searching a Linked List................................
More informationLinked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 3
Steven J. Zeil July 31, 2013 Contents 1 Linked Lists: the Basics 3 2 Coding for Linked Lists 7 2.1 Traversing a Linked List........................... 10 2.2 Searching a Linked List............................
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
More informationComputer Programming with C++ (21)
Computer Programming with C++ (21) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Classes (III) Chapter 9.7 Chapter 10 Outline Destructors
More informationCS 1337 Computer Science II Page 1
Source File: ~/1337/65/lab65.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 3 The purpose of this assignment is to add to the implementation
More informationI/O Streams and Standard I/O Devices (cont d.)
Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined
More informationOperator 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 informationDue 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 informationG52CPP C++ Programming Lecture 17
G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions
More informationA Deeper Look at Classes
A Deeper Look at Classes 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
More informationCSI33 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 informationChapter 10 - Notes Applications of Arrays
Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2015 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationInheritance and Polymorphism
Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data
More informationGetting started with C++ (Part 2)
Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output
More informationEECE.3220: Data Structures Spring 2017
EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based
More informationClasses: A Deeper Look, Part 2
10 But what, to serve our private ends, Forbids the cheating of our friends? Charles Churchill Instead of this absurd division into sexes they ought to class people as static and dynamic. Evelyn Waugh
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming Data is stored in variables CS 2308 Spring 2014 Jill Seaman - Perhaps using arrays and structs. Program is a collection of functions that perform
More informationl 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 Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Fall 2016 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationA C++ Class Designer s Checklist
Steven J. Zeil August 28, 2013 Contents 1 The Checklist 2 2 Discussion and Explanation 3 2.1 Is the interface complete?........ 3 2.2 Are there redundant functions or functions that can be generalized?............................
More informationLab 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 informationFile 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 informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
More informationInput and Output. Data Processing Course, I. Hrivnacova, IPN Orsay
Input and Output Data Processing Course, I. Hrivnacova, IPN Orsay Output to the Screen Input from the Keyboard IO Headers Output to a File Input from a File Formatting I. Hrivnacova @ Data Processing Course
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationCS2141 Software Development using C/C++ Stream I/O
CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make
More informationpointers & 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 informationChapter 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 informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we
More informationCAAM 420 Fall 2012 Lecture 29. Duncan Eddy
CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2012 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationMakefiles Makefiles should begin with a comment section of the following form and with the following information filled in:
CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also
More informationW8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls
1 W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 2 7.4 friend Functions and friend Classes friend function and friend classes Can access private
More informationChapter 18 - C++ Operator Overloading
Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend
More informationAssignment 2 Solution
Assignment 2 Solution Date.h #ifndef DATE_H #define DATE_H #include class Date time_t date; public: Date(); Date(const Date&) = default; Date(time_t); // Date in time_t format Date(const char*);
More informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
More information2. It is possible for a structure variable to be a member of another structure variable.
FORM 1(put name, form, and section number on scantron!!!) CS 162 Exam I True (A) / False (B) (2 pts) 1. What value will the function eof return if there are more characters to be read in the input stream?
More informationStrings 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 informationObject-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering
Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering Lecture 3 Winter 2011/12 Oct 25 Visual C++: Problems and Solutions New section on web page (scroll down)
More informationREVIEW. The C++ Programming Language. CS 151 Review #2
REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,
More informationObject Oriented Programming COP3330 / CGS5409
Object Oriented Programming COP3330 / CGS5409 Multiple Inheritance Template Classes and Functions Inheritance is supported by most object oriented languages C++ allows a special kind of inheritance known
More informationFile I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents
File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or
More information10/23/02 21:20:33 IO_Examples
1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(
More informationPractice Problems CS2620 Advanced Programming, Spring 2003
Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector
More informationl 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 Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Spring 2017 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains
More informationIntroduction 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 information1 // 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>
CISC11 Introduction to Computer Science Dr. McCoy Lecture 20 November, 2009. Using Default Arguments with Constructors Constructors Can specify default arguments Default constructors Defaults all arguments
More informationProgramming. C++ Basics
Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationThe Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.
Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Fall 2014 Jill Seaman The Class A class in C++ is similar to a structure. A class contains members: - variables AND - functions (often called
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure
More information2 nd Week Lecture Notes
2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationG52CPP 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 informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationShahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods
Overloading Operators friend functions static data and methods Shahram Rahatlou Computing Methods in Physics http://www.roma1.infn.it/people/rahatlou/cmp/ Anno Accademico 2018/19 Today s Lecture Overloading
More informationC++ 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 informationSoftware Design Abstract Data Types
Software Design Abstract Data Types 1 Software Design top down, bottom up, object-oriented abstract data types 2 Specifying a ClassClock date and time in a C++ program encapsulating C code public and private
More informationDue Date: See Blackboard
Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with
More information! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.
Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2015 Jill Seaman The Class! A class in C++ is similar to a structure.! A class contains members: - variables AND - functions (often called
More informationG52CPP 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 informationOBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++ 1 Slide 2 Chapter 9 Separate Compilation and Namespaces Created by David Mann, North Idaho College Slide 3 Overview Separate Compilation (9.1) Namespaces (9.2) Slide
More information! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be
Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Spring 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if
More informationOutline. 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 informationRecursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5
Steven Zeil November 25, 2013 Contents 1 Recursion 2 2 Example: Compressing a Picture 4 3 Example: Calculator 5 1 1 Recursion Recursion A function is recursive if it calls itself or calls some other function
More informationInput/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...
Input/output Remember std::ostream? namespace std { class ostream { /*... */ }; } extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; 7 / 24 std::istream std::ostream std
More informationC++ Quick Guide. Advertisements
C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and
More informationtypedef Labeling<unsigned char,short> LabelingBS; typedef Labeling<unsigned char,short>::regioninfo RegionInfoBS;
2005 7 19 1 ( ) Labeling 2 C++ STL(Standard Template Library) g++ (GCC) 3.3.2 3 3.1 Labeling SrcT DstT SrcT: unsigned char, shoft DstT: short typedef 1. unsigned char, short typedef Labeling
More informationC++ Basics. Lecture 2 COP 3014 Spring January 8, 2018
C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing
More informationPiyush 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 informationWhat we will learn about this week:
What we will learn about this week: Streams Basic file I/O Tools for Stream I/O Manipulators Character I/O Get and Put EOF function Pre-defined character functions Objects 1 I/O Streams as an Introduction
More informationC C C C++ 2 ( ) C C++ 4 C C
# 7 11 13 C 4 8 11 20 C 9 11 27 C++ 1 10 12 4 C++ 2 11 12 11 C++ 3 12 12 18 C++ 4 C++ 5 13 1 8 ( ) 14 1 15 C++ 15 1 22 2 (D) ( ) C++ 3 6 Hello C++ 4 5 1. make Makefile.c (arithmetic.c) main main arithmetic
More informationC++_ 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 informationC++ Input/Output: Streams
C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:
More informationLecture 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 informationAbstract 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 informationPointers and References
Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on
More informationFast 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 informationLecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47
Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers
More informationIV. 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
IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two
More informationC++ for Python Programmers
C++ for Python Programmers Adapted from a document by Rich Enbody & Bill Punch of Michigan State University Purpose of this document This document is a brief introduction to C++ for Python programmers
More informationFundamentals of Programming CS-110. Lecture 2
Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout
More information