#include #include #include #include using namespace std; void get_course_list(); void organize_popular_courses(); int get_course_students(vector, int); void print_vector(vector); vector global_list; int main() { get_course_list(); // Display original course information organize_popular_courses(); // Display organized course information system("pause"); return 0; } void print_vector(vector v) { for (int i = 0; i < v.size(); i++) cout << v.at(i) << endl; } /** * Loads the course list into a vector. Each course is in its * own index of the vector. * * Prints the vector before ending. */ void get_course_list() { ifstream fin; fin.open( "Course.txt" ); while ( !fin.eof() ) { string s; getline(fin, s); global_list.push_back(s); } fin.close(); print_vector(global_list); } /** * Swap strings in vector according to the number of students in each course. * Uses the get_course_students() method to compare the number of students * in one course to the number of students in another course. * * Prints the vector before ending. */ void organize_popular_courses() { int first, second, swap; bool unorganized = true; while (unorganized) { first = 0, second = first + 1; swap = 0; /* * Iterate through the list once */ for(int i = 0; i < global_list.size(); i++) { if (second > global_list.size() - 1) // Wrap second back to beginning of the vector second = 0; if (first > global_list.size() - 1) // Wrap first back to beginning of the vector first = 0; if (get_course_students(global_list, first) < get_course_students(global_list, second)) { global_list.at(first).swap(global_list.at(second)); // Swap the two strings cout << "Swapped vector index " << first << " and vector index " << second << "." << endl; print_vector(global_list); //cout << "NOTE: vector begins at index 0. Index numbers != Course numbers." << endl; unorganized = true; } else unorganized = false; first++; second++; } // If no swaps take place, the vector must be organized. if (swap > 0) { unorganized = true; } else unorganized = false; } cout << endl; cout << endl; cout << "Final Output:" << endl; print_vector(global_list); } /** * Counts the numbers of students in each course by counting * the number of words on each line in the text file, then subtracts * 3 from the final answer to eliminate the course number, course name, * and professors name. */ int get_course_students(vector v, int m) { int wordsInString = 1; char nextChar; string course = v.at(m); // get the line we want to count for (int i = 0; i < course.length(); i++) { nextChar = course.at(i); if (isspace(course[i])) wordsInString++; } return wordsInString - 3; // remove 3 from total words in the string }