#include #include #include "apvector.h" const int MAX_BOXES = 100; struct MailInfo { int POBox; int mailCount; // # pieces of mail for this po box MailInfo() : POBox(0), // default constructor mailCount(0) { } MailInfo(int box) // construct with one piece of mail : POBox(box), mailCount(1) { } }; class MailBoxes { public: MailBoxes(); // initial capacity = MAX_BOXES, zero boxes stored void addMail(int poBox); // add one piece for poBox void processMail(istream & input); // process file of po boxes void printAll(ostream & output); private: int boxIndex(int box); // helper function, returns index apvector myBoxes; // list of all poboxes and counts int myBoxCount; // # of itmes stored in myBoxes }; MailBoxes::MailBoxes() : myBoxes(MAX_BOXES), myBoxCount(0) // postcondition: capacity = MAX_BOXES, zero boxes stored { } int MailBoxes::boxIndex(int box) { int k; for(k=0; k < myBoxCount; k++) { if (myBoxes[k].POBox == box) { return k; } } return -1; } void MailBoxes::addMail(int poBox) { int index = boxIndex(poBox); if (index != -1) { myBoxes[index].mailCount++; } else { myBoxes[myBoxCount] = MailInfo(poBox); myBoxCount++; } } void MailBoxes::processMail(istream & input) { int box; while (input >> box) { addMail(box); } } void MailBoxes::printAll(ostream & output) { int k; for(k=0; k < myBoxCount; k++) { output << "box = [" << myBoxes[k].POBox << "] count = " << myBoxes[k].mailCount << endl; } } int main() { MailBoxes boxes; boxes.addMail(123); boxes.addMail(456); boxes.addMail(123); boxes.printAll(cout); cout << "after file processing" << endl; ifstream input("mail.dat"); boxes.processMail(input); boxes.printAll(cout); }