680 likes | 1.18k Views
Data Structures and Algorithms in C++ Michael T. Goodrich Roberto Tamassia David M. Mount. Chapter 1 Basic C++ Programming. Contents . 1.1 Basic C++ Programming Elements 1.2 Expressions 1.3 Control Flow 1.4 Functions 1.5 Classes 1.6 C++ Program and File Organization
E N D
Data Structures and Algorithms in C++ Michael T. GoodrichRoberto TamassiaDavid M. Mount Chapter 1 Basic C++ Programming
Contents • 1.1 Basic C++ Programming Elements • 1.2 Expressions • 1.3 Control Flow • 1.4 Functions • 1.5 Classes • 1.6 C++ Program and File Organization • 1.7 Writing a C++ Program • 1.8 Exercises
1.1 Basic C++ Programming Elements 1.1.1 A Simple C++ Program #include <cstdlib> #include <iostream> /* Inputs two numbers and outputs their sum */ int main( ) { int x , y; std::cout << “Please enter two numbers: “; std::cin >> x >> y; // inputs x and y int sum = x + y; // compute their sum std::cout << “Their sum is “ << sum << std::endl; return EXIT_SUCCESS; // terminates successfully }
1.1 Basic C++ Programming Elements 1.1.2 Fundamental Types bool Boolean value, either true or false char character short, int, long short, normal, long integer float, double single-, double- precision floating-point number void nothing enum enum Color {RED, GREEN, BLUE}
1.1 Basic C++ Programming Elements Pointers char ch = ‘Q’; char* p = &ch; cout << *p; ch = ‘Z’; cout << *p;
1.1 Basic C++ Programming Elements Arrays double f[3]; double* p[10]; f[2] = 25.3; p[4] = &f[2]; cout << *p[4];
1.1 Basic C++ Programming Elements Strings #include <string> using std::string; //… string s = “to be”; string t = “not “ + s; string u = s + “ or “ + t; if (s > t) cout << u;
1.1 Basic C++ Programming Elements C-Stype Structures enumMealType { NO_PREF, REGULAR, LOW_FAT, VEGETARIAN }; struct Passenger { string name; MealTypemealPref; boolisFreqFlyer; string freqFlyerNo; };
1.1 Basic C++ Programming Elements Pointers, Dynamic Memory, and the “new” Operator Passenger *p; //… p = new Passenger; p ->name = “Pocahontas”; p ->mealPref = REGULAR; p ->isFreqFlyer = false; p ->freqFlyerNo = “NONE”;
1.1 Basic C++ Programming Elements 1.1.4 Scope and Namespaces Constants and Typedef const int CUT_OFF[ ] = {90, 80, 70, 60}; const int N_DAYS = 7; const int N_HOURS = 24*N_DAYS; int counter [N_HOURS];
1.1 Basic C++ Programming Elements typedef char* BufferPtr; typedef double Coordinate; BufferPtr p; Coordinate x, y;
1.1 Basic C++ Programming Elements Local and Global Scopes const int cat = 1; int main ( ) { const int cat = 2; cout << cat; return EXIT_SUCCESS; } int dog = cat;
1.1 Basic C++ Programming Elements Namespaces namespace myglobals { int cat; string dog = “bow wow”; } The Using Statement using std::string; using std::cout; usingnamespace myglobals;
1.2 Expressions Member Selection and lndexing class_name . member class/structure member selection pointer -> member class/structure member selection array [exp] array subscripting
1.2 Expressions Arithmetic Operators exp + exp addition exp – exp subtraction exp * exp multiplication exp / exp division exp % exp modulo(remainder)
1.2 Expressions Increment and Decrement Operators var ++ post increment var - - post decrement ++ var pre increment - - var pre decrement
1.2 Expressions Relational and Logical Operators exp < exp less than exp > exp greater than exp <= exp less than or equal exp >= exp greater than or equal exp == exp equal to exp != exp not equal to ! exp logical not exp && exp logical and exp || exp logical or
1.2 Expressions Bitwise Operators ~ exp bitwise complement exp & exp bitwise and exp ^ exp bitwise exclusibe-or exp | exp bitwise or exp1 << exp2 shift exp1 left by exp2 bits exp1 >> exp2 shift exp1 right by exp2 bits
1.2 Expressions Assignment Operators int i = 10; int j = 5; int k = 1; string s = “yes”; i - = 4; j *= -2; k <<= 1; s += “ or no”;
1.2 Expressions class_name::member namespace_name::member bool_exp ? True_exp : false_exp stream >> var stream << exp
1.2 Expressions 1.2.1 Casting in Expressions Traditional C-Style Casting int cat = 14; double dog = (double) cat; double pig = double(cat);
1.2 Expressions Static Casting Static_cast < <desired_type> > ( <expression> ); double d1 = 3.2; double d2 = 3.9999; int i1 = static_cast<int>(d1); int i2 = static_cast<int>(d2);
1.2 Expressions Implicit Casting int = 3; double d = 4.8; double d3 = i / d; int i3 = d3;
1.3 Control Flow If Statement if (<boolean_exp>) <true_statement> [else if (<boolean_exp>) <else_if_statement>] [else <else_statement>]
1.3 Control Flow Switch Statement char command; cin >> command; switch (command){ case ‘I’ : editlnsert(); break; case ‘D’ : editDelete(); break; case ‘R’ : editReplace(); break; default : cout << “Unrecognized command\n”; break; }
1.3 Control Flow While and Do_While Loops while (<boolean_expression>) <loop_body_statement> do <loop_body_statement> while ( <boolean_expression> )
1.3 Control Flow For Loop for ( [<initialization>]; [<condition>]; [<increment>] ) <body_statement> const int NUM_ELEMENTS = 100; float a[NUM_ELEMENTS]; //… for (int i = 0 ; i < NUM_ELEMENTS; i++) { if (a[i] > 0 ) { cout << a[i] << ‘\n’ ;} }
1.3 Control Flow Break and Continue Statements int sum = 0; while (true) { int x; cin >> x; if ( x < 0 ) break; sum += x; } cout << “Sum is “ << x << ‘\n’;
1.4 Fuctions bool evenSum(int a[ ], int n ); int main( ) { const int listLength = 6; int list[ listLength ] = {4, 2, 7, 8, 5, 6}; bool result = evenSum( list, listLength); if (result) cout << “even sum. \n”; else cout << “odd sum. \n”; return EXIT_SUCCESS; } bool evenSum( int a[ ], int n) { int sum = 0; for ( int i = 0 ; I < n ; i++ ) sum += a[ i ]; return (sum % 2 ) == 0; }
1.4 Fuctions 1.4.1 Argument Passing void f(int value, int &ref) { value++; ref++; cout << value << ‘\n’; cout << ref << ‘\n’; } int main( ) { int cat = 1; int dog = 5; f(cat, dog); cout << cat << ‘\n’; cout << dog << ‘\n’; return EXIT_SUCCESS; }
1.4 Fuctions 1.4.2 Overloading Function Overloading void print( int x ) { cout << x; } void print( const Passenger &pass) { cout << pass.name << “ “ << pass.mealPref; if ( pass.isFreqFlyer ) { cout << “ “ << pass.freqFlyerNo; } }
1.4 Fuctions Operator Overloading bool operator == ( const Passenger &x, const Passenger &y ) { return x.name == y.name && x.mealPref == y.mealPref && x.isFreqFlyer == y.isFreqFlyer && x.FreqFlyerNo == y.FreqFlyerNo }
1.4 Fuctions Using Overloading ostream& operator << (ostream &out, const Passenger &pass) { out << pass.name << “ “ << pass.mealPref; if ( pass.isFreqFlyer ) { out << “ “ << pass.freqFlyerNo; } return out; }
1.5 Classes 1.5.1 Class Structure class Passerger { private: string name; MealType mealPref; bool isFreqflyer; string freqFlyerNo; public: //… Passenger( ); bool isFrequentFlyer( ) const { return isFreqFlyer; } void makeFrequentFlyer(const string& newFreqFlyerNo){ isFreqFlyer = true; freqFlyerNo = newFreqFlyerNo; } } ;
1.5 Classes 1.5.2 Constructors class Passenger { private: //… public: Passenger( ); Passenger( const string &nm, MealType mpref, string ffn = “NONE” ); passenger( const Passenger &pass) ; //… };
1.5 Classes 1.5.2 Destructors class Vect { private: int* theVect; int vectSize; public: Vect( int size = 10) { vectSize = size; theVect = new int[ size ]; } //… ~Vect( ) { delete [ ] theVect; } } ;
1.5 Classes 1.5.3 Classes and Memory Allocation Vect a(100); Vect b = a; Vect c; c = a;
1.5 Classes Vect::Vect (const Vect &a) { vectsize = a.vectSize; theVect = new int[ vectSize ]; for (int i = 0; i < vectSize; i++ ) { theVect[i] = a.theVect[i]; } }
1.5 Classes Vect& Vect::operator = (const Vect &a) { if (this != &a) { delete [ ] theVect; vectSize = a.vectSize; theVect = new int[ vectSize ]; for (int i = 0; i < vectSize ; i++ ) { theVect[ i ] = a.theVect[ i ]; } } return *this; }
1.5 Classes 1.5.4 Class Friends and Class Members class SomeClass { private: int secret; public: //… friend ostream& operator << (ostream &out, const SomeClass &x); }; ostream& operator <<(ostream &out, const SomeClass &x); { cout << x.secret; }
1.5 Classes Nesting Classes and Types within Classes class Complex { private: class Node { //… }; //… };
1.5 Classes 1.5.5 The Standard Template Library stack Container with last-in, first-out access queue Container with first-in, first-out access deque Double-ended queue vector Resizeable array list Doubly linked list set Set map Associative array ( dictionary) priority_queue Queue orderde by value
1.6 C++ Program and File Organization CreditCard.h #ifndefCREDIT_CARD_H #define CREDIT_CARD_H #include <string> #include <iostream> using std::string; classCreditCard { private: string number; string name; int limit; double balance;
1.6 C++ Program and File Organization public: CreditCard(string no, string nm, int lim, double bal=0); string getNumber() const { return number; } string getName() const { return name; } double getBalance() const { return balance; } int getLimit() const { return limit; } bool chargeIt(double price); void makePayment(double payment) { balance -= payment; } }; std::ostream& operator<<(std::ostream& out, const CreditCard& c); #endif
1.6 C++ Program and File Organization CreditCard.cpp #include "CreditCard.h“ CreditCard::CreditCard(string no, string nm, int lim, double bal) { number = no; name = nm; balance = bal; limit = lim; } bool CreditCard::chargeIt(double price) { if (price + balance > double(limit)) return false; balance += price; return true; }
1.6 C++ Program and File Organization std::ostream& operator<<(std::ostream& out, const CreditCard& c) { out << "Number = " << c.getNumber() << "\n" << "Name = " << c.getName() << "\n" << "Balance = " << c.getBalance() << "\n" << "Limit = " << c.getLimit() << "\n"; return out; }
1.6 C++ Program and File Organization TestCard.cpp #include <vector> #include "CreditCard.h“ using namespace std; void testCard() { vector<CreditCard*> wallet(10); wallet[0] = new CreditCard("5391 0375 9387 5309", "John Bowman", 2500); wallet[1] = new CreditCard("3485 0399 3395 1954", "John Bowman", 3500); wallet[2] = new CreditCard("6011 4902 3294 2994", "John Bowman", 5000); for (int j=1; j <= 16; j++) { wallet[0]->chargeIt(double(j)); wallet[1]->chargeIt(2 * j); wallet[2]->chargeIt(double(3 * j)); }
1.6 C++ Program and File Organization cout << "Card payments:\n"; for (int i=0; i < 3; i++) { cout << *wallet[i]; while (wallet[i]->getBalance() > 100.0) { wallet[i]->makePayment(100.0); cout << "New balance = " << wallet[i]->getBalance() << "\n"; } cout << "\n"; delete wallet[i]; } } int main() { testCard(); return EXIT_SUCCESS; }
1.7 Writing a C++ Program • Design Responsibility Independence Behaviors • Coding Readability and Style • Testing and Debugging
1.8 Exercises • R-1.1 • R-1.2 • R-1.4 • R-1.10 • R-1.12