Docsity

Sort, Non Member Operations - Data Structures | CSCI 1200, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
CSCI-1200 Computer Science II — Fall 2006
Lecture 5 — Classes II, Sort, Non-member Operators
Review from last week
•C++ classes, member variables and member functions, class scope, public and private
•Nuances to remember
–Within class scope (within the code of a member function) member variables and member functions of
that class may be accessed without providing the name of the class object.
–Within a member function, when an object of the same class type has been passed as an argument, direct
access to the private member variables of that object is allowed (using the ’.’ notation).
•Classes vs. structs
•Designing classes
Today’s Lecture
•Extended example of student grading program
•Passing comparison functions to sort
•Non-member operators
5.1 Example: Student Grades
Our goal is to write a program that calculates the grades for students in a class and outputs the students and their
averages in alphabetical order. The program source code is broken into three parts:
•Re-use of statistics code that we wrote in Lecture 3.
•Class Student to record information about each student, including name and grades, and to calculate averages.
•The main function controls the overall flow, including input, calculation of grades, and output.
// File: main_student.cpp
// Purpose: Compute student averages and output them alphabetically.
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>
#include "student.h"
unsigned int max(unsigned int x, unsigned int y) {
return x>y ? x : y;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Usage:\n " << argv[0] << " infile-students outfile-grades\n";
return 1;
}
std::ifstream in_str(argv[1]);
if (!in_str) {
std::cerr << "Could not open " << argv[1] << " to read\n";
return 1;
}
std::ofstream out_str(argv[2]);
if (!out_str) {
std::cerr << "Could not open " << argv[2] << " to write\n";
return 1;
}
pf3
pf4
pf5
pf8

Partial preview of the text

Download Sort, Non Member Operations - Data Structures | CSCI 1200 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CSCI-1200 Computer Science II — Fall 2006

Lecture 5 — Classes II, Sort, Non-member Operators

Review from last week

  • C++ classes, member variables and member functions, class scope, public and private
  • Nuances to remember
    • Within class scope (within the code of a member function) member variables and member functions of that class may be accessed without providing the name of the class object.
    • Within a member function, when an object of the same class type has been passed as an argument, direct access to the private member variables of that object is allowed (using the ’.’ notation).
  • Classes vs. structs
  • Designing classes

Today’s Lecture

  • Extended example of student grading program
  • Passing comparison functions to sort
  • Non-member operators

5.1 Example: Student Grades

Our goal is to write a program that calculates the grades for students in a class and outputs the students and their averages in alphabetical order. The program source code is broken into three parts:

  • Re-use of statistics code that we wrote in Lecture 3.
  • Class Student to record information about each student, including name and grades, and to calculate averages.
  • The main function controls the overall flow, including input, calculation of grades, and output.

// File: main_student.cpp // Purpose: Compute student averages and output them alphabetically. #include #include #include #include #include #include "student.h"

unsigned int max(unsigned int x, unsigned int y) { return x>y? x : y; }

int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage:\n " << argv[0] << " infile-students outfile-grades\n"; return 1; } std::ifstream in_str(argv[1]); if (!in_str) { std::cerr << "Could not open " << argv[1] << " to read\n"; return 1; } std::ofstream out_str(argv[2]); if (!out_str) { std::cerr << "Could not open " << argv[2] << " to write\n"; return 1; }

int num_homeworks, num_tests; double hw_weight; in_str >> num_homeworks >> num_tests >> hw_weight; std::vector students; Student one_student;

// Read the students, one at a time. while(one_student.read(in_str, num_homeworks, num_tests)) { students.push_back(one_student); }

// Compute the averages. At the same time, determine the maximum name length. unsigned int i; unsigned int max_length = 0; for (i=0; i<students.size(); ++i) { students[i].compute_averages(hw_weight); max_length = max(max_length, students[i].first_name().size() + students[i].last_name().size()); } max_length += 2; // account for the output padding with ", "

// Sort the students alphabetically by name. std::sort(students.begin(), students.end(), less_names);

// Output a header... out_str << "\nHere are the student semester averages\n"; const std::string header = "Name" + std::string(max_length-4, ’ ’) + " HW Test Final"; const std::string underline(header.size(), ’-’); out_str << header << ’\n’ << underline << std::endl;

// Output the students... for (i=0; i<students.size(); ++i) { unsigned int length = students[i].last_name().size() + students[i].first_name().size() + 2; students[i].output_name(out_str); out_str << std::string(max_length - length, ’ ’) << " "; students[i].output_averages(out_str); } return 0; // everything fine }

5.2 Declaration of Class Student

  • Stores names, id numbers, scores and averages. The scores are stored using a vector! Member variables of a class can be other classes!
  • Functionality is relatively simple: input, compute average, provide access to names and averages, and output.
  • No constructor is explicitly provided: Student objects are built through the read function.
  • Overall, the Student class design differs substantially in style from the Date class design. We will see different styles of class designs throughout the semester.
  • Note the helpful convention used in this example: all member variable names end with the “_” character.
  • The special pre-processor directives #ifndef student h , #define student h , and #endif ensure that this files is included at most once per .cpp file.

5.4 Implementation of Class Student

  • The read function is fairly sophisticated and depends heavily on the expected structure of the input data. It also has a lot of error checking. - In many class designs, this type of input would be done by functions outside the class, with the results passed into a constructor. We generally prefer this style because it separates elegant class design from clunky I/O details.
  • The accessor functions for the names are defined within the class declaration in the header file. In this course, you are allowed to do this for one-line functions only! For complex classes, including the definition within the header file has dependency and performance implications.
  • The computation of the averages uses some but not all of the functionality from stats.h and stats.cpp (not included in your handout).
  • Output is split across two functions. Again, stylistically, it is sometimes preferable to do this outside the class.
  • We will discuss the non-member function less_names later in this lecture.

// File: student.cpp // Purpose: Implementation of the class Student #include #include #include #include #include "student.h" #include "stats.h"

// Read information about a student, returning true if the information was read correctly. bool Student::read(std::istream& in_str, unsigned int num_homeworks, unsigned int num_tests) {

// If we don’t find an id, we’ve reached the end of the file & silently return false. if (!(in_str >> id_number_)) return false;

// Once we have an id number, any other failure in reading is treated as an error.

// read the name if (! (in_str >> first_name_ >> last_name_)) { std::cout << "Failed reading name for student " << id_number_ << std::endl; return false; }

unsigned int i; int score;

// Read the homework scores hw_scores_.clear(); for (i=0; i<num_homeworks && (in_str >> score); ++i) hw_scores_.push_back(score); if (hw_scores_.size() != num_homeworks) { std::cout << "Pre-mature end of file or invalid input reading " << "hw scores for " << id_number_ << std::endl; return false; }

// Read the test scores test_scores_.clear(); for (i=0; i<num_tests && (in_str >> score); ++i) test_scores_.push_back(score); if (test_scores_.size() != num_tests) { std::cout << "Pre-mature end of file or invalid input reading " << "test scores for" << id_number_ << std::endl; return false; } return true; // everything was fine

}

// Compute and store the hw, test and final average for the student. void Student::compute_averages(double hw_weight) { double dummy_stddev; avg_and_stddev(hw_scores_, hw_avg_, dummy_stddev); avg_and_stddev(test_scores_, test_avg_, dummy_stddev); final_avg_ = hw_weight * hw_avg_ + (1 - hw_weight) * test_avg_; }

std::ostream& Student::output_name(std::ostream& out_str) const { out_str << last_name_ << ", " << first_name_; return out_str; }

std::ostream& Student::output_averages(std::ostream& out_str) const { out_str << std::fixed << std::setprecision(1); out_str << hw_avg_ << " " << test_avg_ << " " << final_avg_ << std::endl; return out_str; }

// Boolean function to define alphabetical ordering of names. The vector sort // function requires that the objects be passed by CONSTANT REFERENCE. bool less_names(const Student& stu1, const Student& stu2) { return stu1.last_name() < stu2.last_name() || (stu1.last_name() == stu2.last_name() && stu1.first_name() < stu2.first_name()); }

5.5 New C++ in the main function — manipulating strings

  • The statement:

const string header = "Name" + string(max_length-4, ’ ’) + " HW Test Final";

creates a constant string by “adding” (concatenating) existing strings.

  • The expression string(max_length-4, ’ ’) within this statement creates a temporary string but does not associate it with a variable.
  • This is done again during the output of each individual student to create an evenly spaced table.

5.6 Exercise

Add code to the end of the main() function to compute and output the average of the semester grades and to output a list of the semester grades sorted into increasing order.

5.10 A Word of Caution about Operators

  • Operators should only be defined if their meaning is intuitively clear.
  • operator< on Student objects fails the test because the natural ordering on these objects is not clear.
  • By contrast, operator< on Date objects is much more natural and clear.

5.11 Exercise

Write an operator< for comparing two Date objects.

5.12 Another Class Example: Alphabetizing Names

// name_main.cpp // Demonstrates another example with the use of classes, including an output stream operator #include #include #include #include "name.h"

int main() {

std::vector names; std::string first, last;

std::cout <<"\nEnter a sequence of names (first and last) and this program will alphabetize them\n";

while (std::cin >> first >> last) { names.push_back(Name(first, last)); }

std::sort(names.begin(), names.end()); std::cout << "\nHere are the names, in alphabetical order.\n";

for (int i = 0; i < names.size(); ++i) { std::cout << names[i] << "\n"; }

return 0; }

5.13 Name Class Declaration & Implementation

// name.h #include #include

class Name { public:

// CONSTRUCTOR Name(const std::string& fst, const std::string& lst);

// ACCESSORS // Providing a const reference to the string allows the string to be // examined and treated as an r-value without the cost of copying it. const std::string& first() const { return first_; } const std::string& last() const { return last_; }

// MODIFIERS void set_first(const std::string & fst) { first_ = fst; } void set_last(const std::string& lst) { last_ = lst; }

private: // REPRESENTATION std::string first_, last_; };

// operator< to allow sorting bool operator< (const Name& left, const Name& right);

// operator<< to allow output std::ostream& operator<< (std::ostream& ostr, const Name& n);

// name.cpp #include "name.h"

// Here we use special syntax to call the string class copy // constructors instead of calling the default constructor and then // performing an assignment in the body of the constructor function. Name::Name(const std::string& fst, const std::string& lst) : first_(fst), last_(lst) {}

// operator< bool operator< (const Name& left, const Name& right) { return left.last()<right.last() || (left.last()==right.last() && left.first()<right.first()); }

// operator<< is the output stream operator. It takes two arguments: // the stream (such as cout) and the object to be output. The << // operator should always a reference to the output stream to allow a // sequence of outputs in a single statement. std::ostream& operator<< (std::ostream& ostr, const Name& n) { ostr << n.first() << " " << n.last(); return ostr; }