1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iostream>
#include <vector>
#include <iomanip>
struct name_and_score {
static const int MAX_NAMESIZE = 24 ;
char name[MAX_NAMESIZE] = "" ;
int score = 0 ;
};
// return iterator 'pointing to' the highest score in the range [ from, scores.end() )
// invariant: from < scores.end
// we grit our teeth and adhere to this horrible career-teacher style hack
// 'To solve this we will have to make the second parameter a regular iterator,
// even though it could be used to modify the const vector.'
auto iter_to_highest_score( const std::vector<name_and_score>& scores,
std::vector<name_and_score>::iterator from ) {
auto iter_to_highest = from ;
for( auto iter = ++from ; iter != scores.end() ; ++iter )
if( iter_to_highest->score < iter->score ) iter_to_highest = iter ;
return iter_to_highest ;
}
void sortData( std::vector<name_and_score>& scores ) { // iterative selection sort
for( auto iter = scores.begin() ; iter != scores.end() ; ++iter ) {
// swap_indirect( iter, iter_to_highest_score( scores, iter ) ) ;
// this is implemented inline below.
// get an iterator to the element with the highest score
const auto iter_highest = iter_to_highest_score( scores, iter ) ;
if( iter_highest != iter ) { // if it is not already at the beginning
// bring it to the front by swapping the items (using the iterators)
const name_and_score hold = *iter ;
*iter = *iter_highest ;
*iter_highest = hold ;
}
}
}
void displayData( const std::vector<name_and_score>& scores ) { // note: const
// You must use iterators wherever possible to access the vector.
for( auto iter = scores.begin() ; iter != scores.end() ; ++iter ) {
std::cout << std::setw(name_and_score::MAX_NAMESIZE) << iter->name
<< " : " << std::setw(3) << iter->score << '\n' ;
}
}
int main() {
std::vector<name_and_score> scores { {"abcd",23}, {"efgh",69}, {"ijkl",82}, {"mnop",41},
{"qrst",71}, {"uvwx",18}, {"yzab",99}, {"cdef",31} };
std::cout << "---- original -----\n" ;
displayData(scores) ;
std::cout << "\n---- sorted -----\n" ;
sortData(scores) ;
displayData(scores) ;
}
|