我想创建一个映射,它使用迭代器作为键类型并使用整数作为值,如下例所示:
#include <list>
#include <unordered_map>
int main(int argc, char* argv[])
{
typedef std::list<int> ListType;
typedef std::unordered_multimap<ListType::iterator, unsigned int> MapType;
ListType _list;
MapType _map;
_list.push_back(100);
_map.insert(std::make_pair(_list.begin(), 10));
return 0;
}
不幸的是,这会使编译器中止并返回 error C2440: 'conversion' : cannot convert from 'const std::_List_iterator<_Mylist>' to 'size_t'
.无论如何我可以做些什么来实现这一目标?
最佳答案
该错误意味着您必须为特定迭代器类型提供哈希函数。您可以将散列函数作为第三个模板参数传递给 std::unordered_map .
unordered_map
的键也需要一个相等比较器,但是 std::list 的迭代器已经有了,所以您不需要提供自己的。例如:
#include <list>
#include <unordered_map>
#include <cstddef>
typedef std::list<int> ListType;
typedef std::list<int>::iterator ListIterator;
// a very poor hashing functor
struct MyHash {
size_t operator()(const ListIterator&) const {
// provide a useful implementation here!
size_t hash_ = .... ;
return hash_;
//return 0; // compiles, but is useless
}
};
typedef std::unordered_multimap<ListIterator, unsigned int, MyHash> MapType;
int main() {
ListType list_;
MapType map_;
list_.push_back(100);
map_.insert(std::make_pair(list_.begin(), 10));
return 0;
}
关于c++ - 迭代器作为 unordered_multimap 中的键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10893252/