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
|
#include <iostream>
#include <string>
#include <list>
class Person {
private:
std::string name_ ;
std::string birthday_ ;
std::string address_ ;
int phone_ = 0 ;
public:
Person ( std::string name, std::string bday, std::string address, int phone )
: name_(name), birthday_(bday), address_(address), phone_(phone) {}
const std::string& name() const { return name_ ; }
int phone() const { return phone_ ; }
};
bool operator< ( const Person& a, const Person& b ) { return a.name() < b.name() ; }
int main()
{
std::list<Person> lst { { "Sutter", "aaa", "bbb", 111 }, { "Smith", "ccc", "ddd", 222 } } ;
lst.push_back( Person( "Wakely", "eee", "fff", 333 ) ) ; // add wakely
lst.emplace_back( "Nelson", "ggg", "hhh", 444 ) ; // add nelson
lst.sort() ; // default; Person must be LessThanComparable
for( const Person& p : lst ) std::cout << "{ " << p.name() << ", " << p.phone() << " } " ;
std::cout << '\n' ;
// sort with a user provided predicate (Person need not be LessThanComparable)
// sort in descending order of names
lst.sort( [] ( const Person& a, const Person& b ) { return a.name() > b.name() ; } ) ;
for( const Person& p : lst ) std::cout << "{ " << p.name() << ", " << p.phone() << " } " ;
std::cout << '\n' ;
}
|