简体   繁体   中英

STL set of map iterators

I have an stl unordered_map and I would like to store references to elements in that 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.

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 .

Careful with iterator invalidation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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