i am looking for a container, to contain objects like Employee (with info: name, salary, phone ....) that will be possible to once sort it by name (a..z) and other time sort it by salary for example. what is the best way to do it ? i thought about map, but then i define only 1 key to go by would appreciate every idea (not too advanced please ! )
--- update ---
I actually don't need to always maintain 2 STL containers, i would normally have 1 ( say Employees sorted by last name), and upon request, I don't mind making a new STL container, and pushing all the elements to it again, only this time to be sorted by salary, so i can print it by that order. Is it possible to create map1 with name sort, and map2 with salary sort ? if so would love further explanation \ example for defining these 2 maps. I have very little c++ knowledge ( first assignment i got )
using this version of std::sort
template <class RandomAccessIterator, class Compare>
void sort( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
you can sort on whatever field(s) you want, supplying your own comparator. For instance
struct CompareSalary
{
bool operator () ( const Employee& a, const Employee& b ) const
{
return a.salary < b.salary;
}
}
Also since std::sort is compatible with all containers providing a random acess iterator, std::vector will do just fine.
If you want both the sorting criteria to be available at same time you could also look into Boost MultiIndex
Ps: But since you mentioned that you are new to c++ i would not recommend using Boost MultiIndex. Its difficult to understand its syntax
Provide a functional to std::sort
:
bool byName(Employee left, Employee right) {
return left.name < right.name;
}
std::vector<Employee> employees;
std::sort(employees.begin(), employees.end(), byName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With