| Instructor: | David Goldschmidt, Ph.D. |
|---|---|
| Office Hours: | after class |
| Email: | click here to email me |
// alpha.cpp <== click here for file // Example names.txt file serves as input. #include <algorithm> #include <fstream> #include <iostream> #include <string> #include <vector> using namespace std; // use this later.... bool sort_reverse( string const &left, string const &right ); int main( int argc, char* argv[] ) { if ( argc != 3 ) { cerr << "USAGE: " << argv[0] << " <names-in> <names-out>\n"; return 1; } // open a file for reading ifstream names_in( argv[1] ); if ( !names_in ) { cerr << "ERROR: cannot open file " << argv[1] << '\n'; return 1; } // open file for writing ofstream names_out( argv[2] ); if ( !names_out ) { cerr << "ERROR: cannot open file " << argv[2] << '\n'; return 1; } vector<string> names; string one_name; // read from the file while ( names_in >> one_name ) { names.push_back( one_name ); } sort( names.begin(), names.end() ); // sort in reverse order using the sort_reverse() function // sort( names.begin(), names.end(), sort_reverse ); // echo back the sorted list for ( int i = 0 ; i < names.size() ; i++ ) { names_out << names[i] << '\n'; } return 0; } bool sort_reverse( string const &left, string const &right ) { return right < left; // return empl_left.id < empl_right.id; // return empl_left.lname < empl_right.lname; }
Different Ways to Sort:
// factorial.cpp >== click here for file #include <iostream> using namespace std; int factorial( int n ); int factorial_recursive( int n ); int main() { int x; cout << "Enter an integer: "; cin >> x; // cout << x << "! is " << factorial( x ) << endl; cout << x << "! is " << factorial_recursive( x ) << endl; return 0; } int factorial_recursive( int n ) { if ( n == 0 ) { return 1; } else { // n > 0 return n * factorial_recursive( n - 1 ); // e.g. if n is 6: // return 6 * 5 * 4 * 3 * 2 * 1 * 1 } } int factorial( int n ) // THIS ONE IS FASTER (most likely) { int result = 1; for ( int i = n ; i > 1 ; i-- ) { result = result * i; } return result; }
Recursion:
-
/
| 1 if n == 0
n! = <
| n * (n - 1)! if n > 0
\
-
-
/
p | 1 if p == 0
n = < p-1
| n * n if p > 0
\
-
Calling a Function:
Rules for Writing Recursive Functions:
Iteration vs. Recursion: