-1

I need a container which has key value access(like map or unsorted map) but also can be sorted with some way.
Could someone suggest such container?
Example:
I need to store in it for example Employer class value as value and some string id as key which is not equal employer's name.
so I want container be sortable by employer name.

fer y
  • 505
  • 4
  • 19
Ruslan F.
  • 5,498
  • 3
  • 23
  • 42

1 Answers1

2

I suggest to use a plain std::map, e.g.

typedef std::map<std::string, Employer> EmployerMap;
EmployerMap employers;

...and then use some sequence container (e.g. a std::vector) with iterators pointing into the map. Then you sort the sequence container according to your needs:

// Build vector of iterators into map
std::vector<EmployerMap::iterator> v;
v.reserve( employers.size() );
for ( EmployerMap::iterator it, it != employers.end(); ++it ) {
  v.push_back( it );
}

// Sort vector by names of employers.
std::sort( v.begin(), v.end(),
           [](const EmployerMap::iterator &a, const EmployerMap::iterator &b) -> bool {
               return a->name < b->name;
           }
         );
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207