Maps and the Sort Algorithm


Here are a number of example programs that use the Map STL class and the STL sort algorithm.


map example

Here is a map example in which several employees are inserted into the map by name and then an employee named "nels" is found and his age is printed:

#include <iostream> #include <string> #include <map> using namespace std; class employee { public: int age; string name; employee(int emp_age, string emp_name) : age(emp_age), name(emp_name) {} }; main() { map<string, employee *> employee_table; employee_table.insert(make_pair("brad", new employee(43, "brad"))); employee_table.insert(make_pair("nels", new employee(42, "nels"))); employee_table.insert(make_pair("james", new employee(76, "james"))); // insert returns a pair object whose elements are: // 1) an iterator that points to the inserted element, if the insertion // succeeded, and // 2) a bool that indicates whether or not the insertion succeeded. The // insertion succeeds if the key is not already in the map and fails // otherwise // This example shows you the result of trying to insert a second record // with "james" into the map pair<map<string, employee *>::iterator, bool> insertionResult = employee_table.insert(make_pair("james", new employee(39, "james"))); cout << boolalpha << "insertion result for 2nd james = " << insertionResult.second << endl; map<string, employee *>::iterator employee_table_iter; employee_table_iter = employee_table.find("nels"); // the map find method returns an iterator whose "first" field points to // the key and whose "second" field points to the value cout << employee_table_iter->second->age << endl; }

Sorting a Vector of Integers

#include <iostream> #include <vector> #include <algorithm> using namespace std; main() { vector<int> a; a.push_back(5); a.push_back(3); a.push_back(7); a.push_back(9); a.push_back(1); sort(a.begin(), a.end()); for (int i = 0; i < a.size(); i++) cout << a[i] << endl; }

Sorting a Vector of Objects

#include <iostream> #include <vector> #include <algorithm> using namespace std; class employee { public: int age; string name; employee(int emp_age, string emp_name) : age(emp_age), name(emp_name) {} }; // a function that compares two employees and returns true // if the first employee's age is less than the second // employee's age bool emp_compare(const employee *e1, const employee *e2) { return e1->age < e2->age; } main() { vector<employee *> a; a.push_back(new employee(5, "brad")); a.push_back(new employee(3, "ebber")); a.push_back(new employee(7, "smiley")); a.push_back(new employee(9, "lady")); a.push_back(new employee(1, "sunshine")); sort(a.begin(), a.end(), emp_compare); for (int i = 0; i < a.size(); i++) cout << a[i]->age << endl; }