简体   繁体   English

STL套地图迭代器

[英]STL set of map iterators

I have an stl unordered_map and I would like to store references to elements in that map. 我有一个stl unordered_map,我想在该地图中存储对元素的引用。 I would like there to be no duplicate references. 我希望没有重复的引用。 I thought I could create an set of iterators which pointed to elements. 我以为我可以创建一组指向元素的迭代器。 For one I wasn't sure that it would recognise , but even so I got some long template errors which I think boiled down to there being no comparison operator < for iterators. 对于一个我不确定它是否可以识别,但是即使如此,我仍然遇到了一些很长的模板错误,我认为这归结为没有针对迭代器的比较运算符<。

I then tried an unordered set compiling with g++ -std=c++0x but got pages of errors. 然后,我尝试使用g ++ -std = c ++ 0x进行无序编译,但出现错误页面。

How can I achieve this goal? 我怎样才能实现这个目标?

#include <set>
#include <unordered_map>
#include <unordered_set>

int main() {

  typedef std::unordered_map<int, float> umap;
  umap my_map;

  umap::const_iterator itr;
  for (int i=0;i<10000000;i++) {
    my_map[i] = float(i);
  }

 umap::iterator my_it1 = my_map.find(43);
 umap::iterator my_it2 = my_map.find(44);
 umap::iterator my_it3 = my_map.find(44);


 std::unordered_set<umap::iterator> my_its;
 my_its.insert(my_it1); 
 my_its.insert(my_it2);
 my_its.insert(my_it3);

 return 0;
}

Since you are trying to store the iterators in an unordered set, you don't need a comparison operator but rather a hash function. 由于您尝试将迭代器存储在无序集中,因此不需要比较运算符,而需要哈希函数。

I'm guessing, since each distinct iterator will be pointing to a distinct key, you can use the hash value of the key for hashing the iterator. 我猜,由于每个不同的迭代器都指向一个不同的键,因此您可以使用键的哈希值对迭代器进行哈希处理。

struct iterator_hash
{
    size_t operator()(std::unordered_map<int, float>::const_iterator it) const 
    { 
        return std::hash<int>()(it->first); 
    }
};

and instantiate the unordered set as: 并将无序集实例化为:

std::unordered_set<umap::iterator, iterator_hash> my_its;

unordered_set also requires an equality function, but the iterators own operator== should do fine, as long as all the iterators belong to the same unordered_map . unordered_set还需要一个相等函数,但是只要所有迭代器都属于同一个unordered_map ,迭代器自己的operator==就可以了。

Careful with iterator invalidation. 小心迭代器无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM