我正在编写一个哈希表,但遇到了困难。我想用标准容器( vector 、列表等)的内容初始化它,比如 map :
map <string,int> m(a.begin(),a.end())
我有以下类定义:template <class key,class val,class hashik=std_hash> class hash_table
.
我定义了一个构造函数:
template <template <class> class C> hash_table(typename C<pair <key,val> >::iterator first,typename C<pair <key,val> >::iterator last)
{
init();
for(pair <key,val>* it=first;it!=last;++it)
this->operator[](it->first)=it->second;
}
但是它不编译。 没有匹配的调用函数。例如:
vector <pair <string,int> > a;
...
hash_table <string,int> m(a.begin(),a.end()); //compilation error
我做错了什么?您可以推荐我阅读哪些有关模板的书籍?
最佳答案
您试图对您将接受的类型过于具体。要记住的关键是模板只要编译就可以匹配任何东西。如果我正确地破译了你的代码,你就有了这样一个类:
template <typename K, typename V> hash_table { /* ... */ };
这声明了一个哈希表,其键类型为 K
,值类型为 V
。要编写一个接受来自 map 的元素的构造函数,请声明该构造函数,使其也是一个模板:
template <typename Iter>
hash_table(Iter first, Iter last)
{
init();
for (Iter it = first; it != last; ++it)
this->operator[](it->first)=it->second;
}
这将自动匹配任何可以取消引用以获取 first
和 second
成员的迭代器。在标准容器中,包括 map
、multimap
和它们的 unordered_
同类。这应该足以让您入门。
另请注意,当您需要不知道如何拼写的类型时,例如复杂的函数指针或 lambda(您根本不会拼写),这是一个有用的技巧。
关于c++ - 使用 STL 迭代器的模板构造器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064898/