// CS19 C++ Programming // Steve Hodges, Computer Science, Cabrillo College // sthodges@cabrillo.edu // simple example: // input of strings with c++ strings and c strings (character arrays) // sorting with selection sort // selectionSort() has two helper functions: swap() and findMaxIndex() // all three are overloaded to support both string class and char array // code duplicated to make clearer example for both // char arrays and strings // consider use of templates... #include using std::cin; using std::cout; using std::endl; using std::string; const int MAXSIZE = 100; // maximum number of words const int MAXWORDLEN = 16; // maximum length of a word // swap words (character array elements) at index i and j void swap(char a[][MAXWORDLEN], int i, int j){ char temp[MAXWORDLEN]; strncpy(temp, a[i], MAXWORDLEN); strncpy(a[i], a[j], MAXWORDLEN); strncpy(a[j], temp, MAXWORDLEN); } void swap(string a[], int i, int j){ string temp = a[i]; a[i] = a[j]; a[j] = temp; } // return index of max word between 0 and lastIndex int findMaxIndex(char a[][MAXWORDLEN], int lastIndex){ int index = 0; char max[MAXWORDLEN]; strncpy(max, a[index], MAXWORDLEN); for(int i=1; i<= lastIndex; i++){ if (strcmp(a[i], max)<= 0){ index = i; strncpy(max, a[index], MAXWORDLEN); } } return index; } // return index of max word between 0 and lastIndex int findMaxIndex(string a[], int lastIndex){ int index = 0; string max = a[index]; for(int i=1; i<= lastIndex; i++){ if (a[i].compare(max) <= 0){ index = i; max = a[index]; } } return index; } // sort strings in array in descending order void selectionSort(string a[], int size){ for(int i=size-1; i>=0; i--){ swap( a, i, findMaxIndex(a, i) ); } } // sort char arrays in descending order void selectionSort(char a[][MAXWORDLEN], int size){ for(int i=size-1; i>=0; i--){ swap( a, i, findMaxIndex(a, i) ); } } // read up to MAXSIZE strings from STDIN until EOF // and then sort and print them main(){ int size = 0; // uncomment one of the following two lines char array[MAXSIZE][MAXWORDLEN]; // char array test //string array[MAXSIZE]; // string array test while(size< MAXSIZE && cin >> array[size]){ size++; } cout << "-----> " << size << " line" << (size==1?"":"s") << " <---" << endl; selectionSort(array, size); for(int i=0; i