Code /* example03.cpp Dave Klick CIS 250 2011-05-21 Demonstration of classes, heapsort, vector, and file input. */ #include #include #include #include using std::cin; using std::cout; using std::ifstream; using std::vector; using std::string; class Part { string partNumber; int qty; double cost; public: Part(string sku, int quantity, double cost) { partNumber = sku; qty = quantity; this->cost = cost; } double getTotalCost() { return qty * cost; } string toString() { // formats Part as: sku: qty * cost = total // xxxxxx: ##### * #####.## = ######.## char* pStr = new char[200]; sprintf(pStr, "%6s: %5d * %8.2f = %9.2f", partNumber.c_str(), qty, cost, getTotalCost()); string s(pStr); return s; } int compareTo(Part& p) { if (partNumber > p.partNumber) return 1; if (partNumber < p.partNumber) return -1; return 0; } }; void siftDown(vector& parts, int k, int bottom) { Part tmp = parts[k-1]; while (k <= bottom/2) { int j = k + k; if ((j < bottom) && (parts[j-1].compareTo(parts[j])<0)) j++; if (tmp.compareTo(parts[j-1]) >= 0) break; else { parts[k-1] = parts[j-1]; k = j; } } parts[k-1] = tmp; } void heapSort(vector& parts) { int len = parts.size(); for (int i=len/2; i>0; i--) siftDown(parts, i, len); do { Part tmp = parts[0]; parts[0] = parts[len-1]; parts[len-1] = tmp; len--; siftDown(parts, 1, len); } while (len>1); } void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } int main() { vector vect; int i; string strPartNum, strQty, strCost; ifstream infile("parts.txt"); if (!infile) { cout << "Error opening file\n"; return 1; } while (getline(infile, strPartNum, '|')) { getline(infile, strQty, '|'); getline(infile, strCost, '\n'); Part part(strPartNum, atoi(strQty.c_str()), atof(strCost.c_str())); vect.push_back(part); } infile.close(); heapSort(vect); for (i=0; i