初学STL, 当编译以下代码时,出现错误“error C2783: 'elementType maxElement(containerType &)': could not deduce template argument for 'elementType'”,请各位大虾指教。#include <vector>
#include <iostream>
using namespace std;template<typename elementType, typename containerType>
elementType maxElement(containerType &container)
{
//don't deal with empty container containerType<elementType>::iterator itr = container.begin();
elementType maxValue = *itr;
itr++; for(;itr!=container.end(); itr++)
{
if(*itr > maxValue)
maxValue = *itr;
} return maxValue;
}int main()
{
int intValues[] = {1,2,6,4};
vector<int> intVector(intValues, intValues+4);
cout << maxElement(intVector) << endl;
return 0;
}
#include <iostream>
using namespace std;template<typename elementType, typename containerType>
elementType maxElement(containerType &container)
{
//don't deal with empty container containerType<elementType>::iterator itr = container.begin();
elementType maxValue = *itr;
itr++; for(;itr!=container.end(); itr++)
{
if(*itr > maxValue)
maxValue = *itr;
} return maxValue;
}int main()
{
int intValues[] = {1,2,6,4};
vector<int> intVector(intValues, intValues+4);
cout << maxElement(intVector) << endl;
return 0;
}
containerType已经是一个具体的容器了,containerType<elementType>肯定是不对的,elementType可以从containerType::value_type得出。
#include <vector>
#include <iostream>using namespace std;template <typename containerType>
containerType::value_type maxElement(containerType &container)
{
//don't deal with empty container
typedef typename containerType::value_type elementType;
containerType::iterator itr = container.begin();
elementType maxValue = *itr;
itr++; for (;itr!=container.end(); itr++)
{
if (*itr > maxValue)
maxValue = *itr;
} return maxValue;
}int main()
{
int intValues[] = {1,2,6,4};
vector <int> intVector(intValues, intValues+4);
cout << maxElement(intVector) << endl;
return 0;}
但使用你提供的代码后,原来的error没了,但出现了新的问题。
1.error C2146: syntax error: missing ';' befor identifier 'maxElement'
2.error C4430: missing type specifier - int assumed. Note: C++ does not support default int
3.fatal error C1903: unable to recover from previous error(s); stoping compilation
问题是在containerType::value_type maxElement(containerType &container)
之前的代码可以在BCB里通过,GCC死活不肯,晕~~,下面的代码没问题了#include <vector>
#include <iostream>using namespace std;template <typename containerType>
typename containerType::value_type maxElement(containerType &container)
{
//don't deal with empty container
typedef typename containerType::value_type elementType;
typedef typename containerType::iterator iterator;
iterator itr = container.begin();
elementType maxValue = *itr;
itr++; for (;itr!=container.end(); itr++)
{
if (*itr > maxValue)
maxValue = *itr;
} return maxValue;
}int main()
{
int intValues[] = {1,2,6,4};
vector<int> intVector(intValues, intValues+4);
cout << maxElement(intVector) << endl;
return 0;}