vector用作函数模板形参时出现的一个错误

代码如下:

#include<iostream>
#include<string>
#include<vector>
#include<iterator>
using namespace std;

template<class T>
int find(vector<T> &vec,T data)
{
int index=0;
vector<T>::iterator iter;
for(iter=vec.begin();iter!=vec.end();iter++)
{
if(*iter==data)
break;
else
index++;
}

return index;
}

int main()
{
vector<int> vec1;
int i=0;
for(i=0;i<10;i++)
vec1.push_back(i);
vector<string> vec2;
vec2.push_back("zhang");
vec2.push_back("yong");
vec2.push_back("jian");
int ret;
ret=find(vec1,5);
if(ret==vec1.size())
cout<<"no found"<<endl;
else
cout<<"found,index="<<ret<<endl;
ret=find(vec2,string("kang"));
if(ret==vec2.size())
cout<<"no found"<<endl;
else
cout<<"found,index="<<ret<<endl;

return 0;
}

出现的错误如下:

16_9.cpp: In function `int find(std::vector<T, std::allocator<_CharT> >&, T)':
16_9.cpp:14: error: expected `;' before "iter"
16_9.cpp:15: error: `iter' was not declared in this scope
16_9.cpp: In function `int find(std::vector<T, std::allocator<_CharT> >&, T) [with T = int]':
16_9.cpp:38: instantiated from here
16_9.cpp:14: error: dependent-name ` std::vector<T,std::allocator<_CharT> >::iterator' is parsed as a non-type, but instantiation yields a type
16_9.cpp:14: note: say `typename std::vector<T,std::allocator<_CharT> >::iterator' if a type is meant
16_9.cpp: In function `int find(std::vector<T, std::allocator<_CharT> >&, T) [with T = std::string]':
16_9.cpp:43: instantiated from here
16_9.cpp:14: error: dependent-name ` std::vector<T,std::allocator<_CharT> >::iterator' is parsed as a non-type, but instantiation yields a type
16_9.cpp:14: note: say `typename std::vector<T,std::allocator<_CharT> >::iterator' if a type is meant

经过在Google上查询了一番,得知:

运用 vector<T>内部类型iterator时须要添加typename,加上typename后编译通过。
将上面代码中的红色部分改为下面的代码,编译没有错误。

typename vector<T>::iterator iter;
typename两种用法:

  1。用在模板声明中,如下两个声明是一样的:

template<class T> class Widget; // uses "class"
template<typename T> class Widget; // uses "typename"

  2.用于标识 nested dependent type name(嵌套依赖类型名)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值