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
#include
#include
Sorting a Vector of Integers
#include
#include
#include
using namespace std;
main() {
vector 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
#include
#include
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 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;
}