书上说函数模板会对行参根据实参进行类型的推演.
但本人的实参 vector<char>::iterator beg1
行参 :typename vector<T>::iterator
编译器并没有推出T是char .提示匹配不到函数原形.
最后加入一个 T _value 参数进去,才ok了.
想问问.怎么能不添加 T _value,这个对本人函数没有意义的行参,让函数编译通过?
红色部分是本人不想要的.
template <typename T>
int myFind2(typename vector<T>::iterator _begin,typename vector<T>::iterator _end,T _value)
{
int result=0;
–_begin;
map<T,int> word_count;
while(–_end!=_begin)
{
if(word_count.count(*_end)==0)
{
word_count.insert(make_pair(*_end,1));
}
else
{
++word_count[*_end];
}
}
typename map<T,int>::const_iterator beg=word_count.begin();
while(beg!=word_count.end())
{
cout<<beg->first<<beg->second<<endl;
++beg;
}
return result;
}
int main (int argc,char *argv[])
{
vector<char> inttest;
inttest.push_back(“a”);
inttest.push_back(“b”);
inttest.push_back(“c”);
inttest.push_back(“d”);
inttest.push_back(“b”);
vector<char>::iterator beg1=inttest.begin();
vector<char>::iterator end1=inttest.end();
但本人的实参 vector<char>::iterator beg1
行参 :typename vector<T>::iterator
编译器并没有推出T是char .提示匹配不到函数原形.
最后加入一个 T _value 参数进去,才ok了.
想问问.怎么能不添加 T _value,这个对本人函数没有意义的行参,让函数编译通过?
红色部分是本人不想要的.
template <typename T>
int myFind2(typename vector<T>::iterator _begin,typename vector<T>::iterator _end,T _value)
{
int result=0;
–_begin;
map<T,int> word_count;
while(–_end!=_begin)
{
if(word_count.count(*_end)==0)
{
word_count.insert(make_pair(*_end,1));
}
else
{
++word_count[*_end];
}
}
typename map<T,int>::const_iterator beg=word_count.begin();
while(beg!=word_count.end())
{
cout<<beg->first<<beg->second<<endl;
++beg;
}
return result;
}
int main (int argc,char *argv[])
{
vector<char> inttest;
inttest.push_back(“a”);
inttest.push_back(“b”);
inttest.push_back(“c”);
inttest.push_back(“d”);
inttest.push_back(“b”);
vector<char>::iterator beg1=inttest.begin();
vector<char>::iterator end1=inttest.end();
myFind2(beg1,end1,“a”);
return 0;
}
解决方案
25
全部stl容器都有value_type的类型成员,假如想获取std::vector<T>中T的类型,就是std::vector<T>::value_type
15
map<decltype(*iterator), int> word_count;