C++ examples for STL:map
Using your own sorting functor
#include <iostream> #include <map> #include <string> using namespace std; class FullName {/*w w w . j ava 2s . c o m*/ friend class FullNameLessThan; public: FullName(const string& first, const string& last) : lastName_(last), firstName_(first) {} string getFirstName() const {return(firstName_);} string getLastName() const {return(lastName_);} private: string lastName_; string firstName_; }; class FullNameLessThan { public: bool operator()(const FullName& per1, const FullName& per2) const { if (per1.lastName_ < per2.lastName_) return(true); else if (per1.lastName_ == per2.lastName_) return(per1.firstName_ < per2.firstName_); else return(false); } }; int main() { map<FullName, string, FullNameLessThan> personMap; FullName per1("B", "S"), per2("J", "G"), per3("F", "S"), per4("A", "G"); personMap[per1] = "cool"; personMap[per2] = "not cool"; personMap[per3] = "not cool"; personMap[per4] = "cool"; for (map<FullName, string, FullNameLessThan>::const_iterator p = personMap.begin(); p != personMap.end(); ++p) { cout << p->first.getFirstName() << " " << p->first.getLastName() << " is " << p->second << endl; } }