leo
leo

Reputation: 1117

Set custom comparison type

I am using multisets (sets would be the same), and have them as arguments to a bunch of functions. My functions looked like this:

void insert(const int val, multiset<int>& low, multiset<int>& high)

Then I found out I needed a custom comparison function for one of the multisets. I did it declaring a struct and overriding the () operator.

My multiset definition that once was: multiset<int> low now is multiset<int, order> low.

The problem with this is that I'm actually changing the type of low, and thus I need to change it in every single parameter, which greatly reduces the generality of my functions (the functions do not need to know the comparison method of the multiset).

Moreover, order is one comparison function, which is different from any other comparison functions I might ever declare (even though the types it compare are the exact same). What I mean is that multiset<int, order1> != multiset<int, order2>, which is very bad.

So, my question is, how can I not have this problem? How can I declare functions that accept multisets (or sets) regardless of their comparison function?

Upvotes: 2

Views: 177

Answers (2)

aschepler
aschepler

Reputation: 72356

If possible, I would use templates to take an arbitrary container or iterators.

If you really need it to not be a template and be able to deal with different types of multiset, boost::any_range provides a type-erased container abstraction that might be useful.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

You could use function templates:

template <typename M1, typename M2>
void insert(const int val, M1& low, M2& high);

Another option, if you want to restrict yourself to std::multiset<int, X>, is to use template template parameters.

Upvotes: 2

Related Questions