#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
template<typename T>
void factorial(vector<T> ivec, vector<T>::iterator iter) {
while (iter != ivec.end()) {
cout << *iter << endl;
++iter;
}
}
int main() {
vector<int> ivec = { 1,2,3,4,5,6,7 };
factorial(ivec, ivec.begin());
return 0;
}
在VS 2017中他的报错信息如下:
警告 C4346 “std::vector<T,std::allocator<_Ty>>::iterator”: 依赖名称不是类型 practice_needForCpp11 d:\practice_needforcpp11\practice_needforcpp11\源.cpp 8
错误 C2061 语法错误: 标识符“iterator” practice_needForCpp11 d:\practice_needforcpp11\practice_needforcpp11\源.cpp 8
错误 C2672 “factorial”: 未找到匹配的重载函数 practice_needForCpp11 d:\practice_needforcpp11\practice_needforcpp11\源.cpp 18
错误 C2780 “void factorial(std::vector<T,std::allocator<_Ty>>)”: 应输入 1 个参数,却提供了 2 个 practice_needForCpp11 d:\practice_needforcpp11\practice_needforcpp11\源.cpp 18
请教各位一下这里出了什么问题~谢谢了~~
在Vs2008上运行,会报错。
错误的原因有:
(1)vector<int> ivec = { 1,2,3,4,5,6,7 }; vector不能直接这样初始化赋值。可以用这样来替换
(2)函数写的很不好,直接用这样写就行了,根本没必要传ivec.begin()给函数。因为你已经传了ivec给函数,函数就会得到ivec的所有信息,不必画蛇添足。
如果你非要画蛇添足的做法,可以这样写,至于为什么要加个&符号,是因为不引用的的话就会新建个vector,那么新建的vector里面是没有数据的,所以就肯定错了。