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.
精彩评论