简体   繁体   English

使用STL迭代器的模板构造器

[英]Template Constructor using STL iterators

I'm writting a hash table, but I've faced with a difficulty. 我正在写一个哈希表,但遇到了困难。 I want to initialize it with contents of standart containers(vector, list and etc.), like a map: 我想用标准容器(矢量,列表等)的内容来初始化它,如地图:
map <string,int> m(a.begin(),a.end())
I have the following definition of class: template <class key,class val,class hashik=std_hash> class hash_table . 我对类有以下定义: template <class key,class val,class hashik=std_hash> class hash_table
And I define a constructor: 然后定义一个构造函数:

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;
}

But it doesn't compile. 但是它不能编译。 No matching function for call. 没有匹配的通话功能。 For example: 例如:

vector <pair <string,int> > a;
...
hash_table <string,int> m(a.begin(),a.end()); //compilation error

What am I doing wrong? 我究竟做错了什么? And what books about templates can you advise me to read? 您可以建议我阅读哪些有关模板的书?

You're trying to be too specific about what types you'll accept. 您尝试对接受的类型过于具体。 The key thing to remember is that templates will match just about anything as long as it compiles. 要记住的关键是模板只要编译就可以匹配任何东西。 If I'm deciphering your code correctly, you have a class like this: 如果我正确地解密了您的代码,则您将拥有一个像这样的类:

template <typename K, typename V> hash_table { /* ... */ };

This declares a hash table with keys of type K and values of type V . 这将声明一个哈希表,其键类型为K ,值类型为V To write a constructor that accepts elements from a map, declare the constructor so it is a template too: 要编写一个接受映射元素的构造函数,请声明该构造函数,使其也成为模板:

template <typename Iter>
hash_table(Iter first, Iter last)
{
    init();
    for (Iter it = first; it != last; ++it)
        this->operator[](it->first)=it->second;
}

This will automagically match any iterator that can be dereferenced to get first and second members. 这将自动匹配可以取消引用以获取first成员和second成员的任何迭代器。 Among standard containers, that includes map , multimap and their unordered_ cousins. 在标准容器中,包括mapmultimap及其unordered_表兄弟。 That should be enough to get you started. 那应该足以让您入门。

Also note that this is a useful trick for when you need a type that you don't know how to spell, such as a complicated function pointer or a lambda (which you can't spell at all). 还要注意,当您需要一种不知道如何拼写的类型(例如复杂的函数指针或lambda(您根本无法拼写))时,这是一个有用的技巧。

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

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