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.

有帮助吗?

解决方案

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.

其他提示

Sure it makes sense, if it makes sense in your program.

The Standard doesn't mind if you have a multimap with duplicate values:

23.3.2 Class template multimap

1/A multimap is a kind of associative container that supports equivalent keys (possibly containing multiple copies of the same key value) and provides for fast retrieval of values of another type T based on the keys.

The multimap class supports bidirectional iterators.

So the question isn't if this makes sense from a language perspective -- the question is does it make sense in terms of what you are trying to do?

Off the top of my head I can see this making sense if you want a count of the number of items of a particular value associated with a single key. Perhaps each value might compare equal and still have different attributes (ex: student roster where equality is determined based on name. Foolish, perhaps, but possible.)

It occurs to me that there is at least some similarity between a map with duplicate values and a hash map. There are some obvious differences as well, least of which being domain applicability, but enough similarity to make me think if you are considering having a multimap with duplicate values, you might actually need a hash map (unordered_map in C++11).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top