#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;
}
His error message in VS 2017 is as follows:
警告 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
Could you tell me what went wrong here~Thank you~~
巴扎黑2017-06-23 09:16:59
Change two positions,
Before the change: void factorial(vector<T> ivec, vector<T>::iterator iter)
After the change: void factorial(vector<T> & ivec, typename vector<T>::iterator iter)
Let’s talk about the second change position first. What is typename for? Reference http://blog.csdn.net/laojiu_/...
I can’t explain the location of the first change. If it is not quoted, VS will report a type mismatch when comparing with end(). I don’t understand this either. . .
曾经蜡笔没有小新2017-06-23 09:16:59
When running on Vs2008, an error will be reported.
The reasons for the error are:
(1) vector<int> ivec = {1,2,3,4,5,6,7}; vector cannot be initialized and assigned directly like this. You can replace it with this
vector<int> ivec;
for(int i=1;i<8;i++){
ivec.push_back(i);
}
(2) The function is not well written. Just write it like this. There is no need to pass ivec.begin() to the function. Because you have already passed ivec to the function, the function will get all the information of ivec without adding any extraneous information.
#include "iostream"
#include <vector>
using namespace std;
void factorial(vector<int> ivec) {
vector<int>::iterator it;
for(it=ivec.begin();it!=ivec.end();it++)
cout<<*it<<endl;
}
int main()
{
vector<int> ivec;
for(int i=1;i<8;i++){
ivec.push_back(i);
}
factorial(ivec);
return 0;
}