Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL container with more than 1 sorting method in c++

Tags:

c++

stl

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 )

like image 998
RanH Avatar asked Sep 02 '10 13:09

RanH


3 Answers

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.

like image 129
stijn Avatar answered Sep 28 '22 09:09

stijn


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

like image 32
Yogesh Arora Avatar answered Sep 28 '22 09:09

Yogesh Arora


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);
like image 31
Philip Potter Avatar answered Sep 28 '22 08:09

Philip Potter