Search code examples
c++stlmultimap

Does a multimap with the key and the value being of the same type make any sense?


Does a std::multimap make any sense if the key and the value of it are of the same type?

The real code is much more complicated, but for example, I have a class Point and I want to find similar objects of that type:

bool
ComparePoints::operator()(Point* const p1, Point* const p2) const {
  if (p1->x > p2->x) return false;
  if (p1->x < p2->x) return true;
  ...
  return false;
}

I can use a std::multimap with comparison function for that purpose, and then using MultiMap::equal_range get a group of objects.

std::multimap<Point*, Point*, ComparePoints> pointsMap;

This work fine for me, but I kind of feel that the value field has become redundant. Do I need to seek for a better solution?

Edited:

I'm mapping from an object to the exact same object

pointsMap.insert(std::pair<Point*, Point*>(p, p));

making the value redundant, so I probably should use std::multiset instead as @john mentioned.


Solution

  • This makes sense.

    For example, I want to cross-reference all restaurants in a city within a certain proximity to restaurants I own. The data type in this data structure will be the same, however, the grouping of the entities is significant in my business logic and criteria.

    When you are using a hash data type, you are essentially grouping objects by a common key. It doesn't matter if the key is the same type or not. To say, "I want to group all points by this one reference point," is a legitimate use of that data type.