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.
Asked
Active
Viewed 117 times
-1
-
Do you mean it must be sortable *after* construction? – juanchopanza Aug 21 '13 at 11:52
-
Well, `std::map` *is* sorted "in some way" (ie. according to its keys). If that's not what you want, please make your question clearer. – syam Aug 21 '13 at 11:52
-
I've provided some exmaple... – Ruslan F. Aug 21 '13 at 11:54
-
@syam I know that map is sorted by key but such sorting don't fit me. – Ruslan F. Aug 21 '13 at 11:56
-
Did you take a look at boost multi index container? http://www.boost.org/doc/libs/1_54_0/libs/multi_index/doc/index.html. Could be what you are looking for. – mkaes Aug 21 '13 at 11:57
1 Answers
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