0

I have a class S which is stored in a std::multimap<int, S>:

class S{
    int _secondKey{0};
    int _thirdKey{0};
};

I would like to store elements of the same key, sorted based on the _secondKey class member and then _thirdKey member.

Is this possible to do in C++? I am using GCC 5.3

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user997112
  • 29,025
  • 43
  • 182
  • 361
  • Specifically using `multimap`? No. [The elements with duplicate key will be stored in insertion order](http://en.cppreference.com/w/cpp/container/multimap/insert). – BoBTFish Mar 09 '17 at 13:48
  • I started to write an implementation based on std::map> but you'll need to write a custom getter and setter and iterators if you want to hide the bookkeeping like creating an empty set when you make a new key, and things like that. – Kenny Ostrom Mar 09 '17 at 18:57
  • In C++14 you could use a `std::multiset, std::less<>>`. That has nearly the interface you seem to want. – Deduplicator Oct 11 '18 at 15:27

2 Answers2

1

Possible solution is to have std::map<int,std::vector<S>> instead of std::multimap<int, S> and sort as you need when insert:

 S newvalue = ...;
 auto &v = mymap[ newvalue._secondKey ];
 auto it = std::lower_bound( v.begin(), v.end(), newvalue, thirdKeyCmp );
 v.insert( it, newvalue );

or simply use std::set<S> with custom comparator that sorts by second and third key:

bool cmpS( const S &s1, const S &s2 ) {
     return std::tie( s1._secondKey, s1._thirdKey ) < std::tie( s2._secondKey, s2._thirdKey );
}

using myset = std::set<S,cmpS>;
Slava
  • 43,454
  • 1
  • 47
  • 90
0

It's not possible, but you can create another std::multimap object with keys and values flipped (so that value_type is key_type) if you need the map sorted like that only for a moment for specific operations. It is well shown here.

Community
  • 1
  • 1
Criss
  • 581
  • 5
  • 17