6

std::unordered_multimap在处理迭代时,我想知道一个关键对象的唯一性。

我将尝试解释这一点:我需要将一些数据与映射中的键类型相关联,这些数据不应考虑在HashorKeyEqual元素中,但我需要它以避免与它存储单独的映射(出于优化目的) .

所以与我的想法相关的代码如下:

struct Key {
  void* data;
  mutable bool attribute;

  Key(void* data) : data(data), attribute(false) { }
  bool operator==(const Key& other) const {
    return data == other.data;
  }
};

struct KeyHash {
  size_t operator()(const Key& key) const {
    return std::hash<void*>()(key.data);
  }
};

class Foo {
public:
  int i;
  Foo(int i) : i(i) { }
};

std::unordered_multimap<Key, Foo, KeyHash> map;

问题源于这样一个事实,尽管这工作正常,但不能保证作为std::pair<const Key, Foo>映射到单个元素的第一个元素检索到的键始终相同。作为其中的一个pairconst Key听起来地图中的每个元素都有其键值的副本,所以如果我这样做

void* target = new int();
map.emplace(std::make_pair(target, Foo(1)));
map.emplace(std::make_pair(target, Foo(2)));


auto pit = map.equal_range(target);
pit.first->first.attribute = true;  
std::cout << std::boolalpha << (++pit.first)->first.attribute << endl;

false证实了我的想法。因此,如果您有多个具有相同键的值(这是您想要的,因为您使用的是 ),那么确实会浪费大量空间来存储键std::unordered_map

我没有看到任何其他解决方案,而不是类似

struct Value
{
  std::vector<Foo> foos;
  bool attribute;
};

std::unordered_map<void*, Value> map;

这允许我将属性与键配对,但由于它需要使用两个级别的迭代器,所以一切都变得不那么干净了。

还有其他我没有看到的解决方案吗?

4

1 回答 1

2

23.5.5.1 类模板 unordered_multimap 概述 [unord.multimap.overview]

1 unordered_multimap 是一个无序关联容器,它支持等效键(unordered_multimap 的一个实例可能包含每个键值的多个副本),并将另一种类型 mapped_type 的值与键相关联。unordered_multimap 类支持前向迭代器。

Anunordered_multimap可能包含密钥的多个副本,如果您想要密钥的单个副本,那么可能 aunordered_map<K, vector<V>>可能更合适。

于 2016-09-25T23:21:29.643 回答