1

I have a paired key map named mymap and I have defined a comparison operator named cmplt_cmprsn shown below

#include <iostream>
#include <map>

struct prtl_cmprsn {

  bool operator()(
    const std::pair<int64_t, int64_t> &left,
    const std::pair<int64_t, int64_t> &right) const
  {
    return left.first > right.first;
  }
};

struct cmplt_cmprsn {

  bool operator()(
    const std::pair<int64_t, int64_t> &left,
    const std::pair<int64_t, int64_t> &right) const
  {
    return left.first != right.first
      ? left.first > right.first
      : left.second > right.second;
  }
};

int main ()
{
  std::map<std::pair<int64_t, int64_t>, double, cmplt_cmprsn> mymap;
  return 0;
}

which provides a complete comparison between unique paired keys that are used in mymap.

I want to perform two separate iterations through mymap:

(1) iterate over all unique paired keys in one full iteration

(2) find all unique first sub-keys and iterate over unique paired keys sharing those first sub-keys in two nested iterations.

I can write a partial comparison operator named prtl_cmprsn shown above. However, mymap already has been defined using cmplt_cmprsn operator. Is there a way to switch comparison operators after the map is defined, or having multiple comparison operators is not possible in this context?

linuxfreebird
  • 799
  • 2
  • 8
  • 16
  • 1
    `template<,double> T>` - huh? – Fureeish Sep 07 '19 at 10:45
  • 1
    The first as well as the second exposed code for the `bool operator()` is just a syntax error. Furthermore, a predicated for `std::map,double,cmplt_cmprsn>` should accept two arguments of `const std::pair&` - the type `double` of value is wrong. Btw. all the `if`s blow the code IMHO - I would do shorter: [**Demo on coliru**](http://coliru.stacked-crooked.com/a/76056cd888ca7ebd). – Scheff's Cat Sep 07 '19 at 11:05
  • For `prtl_cmprsn`, a [`std::multimap`](https://en.cppreference.com/w/cpp/container/multimap) (which accepts duplicated keys) might be the better choice. – Scheff's Cat Sep 07 '19 at 11:07
  • 1
    If you want a range that share the first key, you call can essentially call `lower_bound` with a key of { key1, - infinity } and again with { key + 1, -infinity } provided that key cannot be equal to + infinity. However, you might also simply find the start of the range and then break out of the loop when the value of the first key does not match anymore. – Phil1970 Sep 07 '19 at 13:46
  • @Scheff Thanks for the clarification. I have included your code in my OP. – linuxfreebird Sep 07 '19 at 15:16

0 Answers0