/* * John W. Clark * * sample stl problem for acm presentation * DISCLAIMER : I am in no way endorsing a candidate or party * the sample numbers I used were pulled off the web * at around 1:30 am on Wed 11-3-04 and do reflect anything */ #include #include #include using namespace std; typedef pair< string, pair< int, int > > arg; typedef vector< arg > storage; typedef storage::iterator iter; typedef storage::const_iterator citer; static const int indent[] = { 20, 15, 15 }; ostream & operator << ( ostream & ost, const arg & a ) { ost << setw(indent[0]) << left << a.first << right << setw(indent[1]) << a.second.first << setw(indent[2]) << a.second.second; return ost; } ostream & operator << ( ostream & ost, const storage & s ) { ost << setw(indent[0]) << left << "state" << right << setw(indent[1]) << "republican" << setw(indent[2]) << "democrat" << endl; for ( citer i = s.begin(); i != s.end() ; ++i ) ost << *i << endl; return ost; } bool rep_states ( storage::value_type & foo ) { return ( foo.second.second < foo.second.first ); } template < class T > class Print { public: ostream & os; Print( ostream & o = cout ) : os(o) {} void operator() (T & x) { os << x << endl; } }; int main() { storage store; string line; char ch; // all valid input lines are of the form // state name republican_votes democrat_votes string state; int rep, dem; while ( cin.get(ch) ) { if ( isdigit( ch ) ) { cin.putback(ch); if ( cin >> rep >> dem ) store.push_back( make_pair ( state, make_pair( rep, dem ))); else cerr << "invalid input" << endl; // either way I am done with this line getline( cin, state ); // clear out the rest of this line state = ""; // reset the state name } else { state += ch; } } sort( store.begin(), store.end() ); cout << "all states" << endl; cout << store << endl; // partition by which part won iter rep_end = partition ( store.begin(), store.end(), rep_states ); storage elephants ( store.begin(), rep_end ); storage donkeys ( rep_end, store.end() ); // sort and output them cout << "Republican party states" << endl; sort( elephants.begin(), elephants.end() ); for_each ( elephants.begin(), elephants.end(), Print(cout) ); cout << endl; cout << "Democratic party states" << endl; sort( donkeys.begin(), donkeys.end() ); for_each ( donkeys.begin(), donkeys.end() , Print(cout) ); cout << endl; // total the votes pair< int, int > votes(0,0); for ( citer i = store.begin() ; i != store.end() ; ++i ) { votes.first += i->second.first; votes.second += i->second.second; } storage total; total.push_back( make_pair ( "total", votes ) ); cout << *total.begin() << endl; return 0; }