【发布时间】:2021-02-14 12:32:38
【问题描述】:
我正在解决 STL 容器中的一个问题:
创建一个 Sum() 函数来计算两个迭代器之间的和。然后该函数使用迭代器类型的模板参数并接受两个迭代器,开始和结束
我正在尝试编写以下代码,但我不明白这个问题,谁能帮助我。
template <typename type , typename start , typename end>
double sum(type& t, start& s , end& e)
{
typename t::const_iterator i;
double sum = 0;
for (i = s ; i != e; ++i)
{
sum+=*i;
}
return sum;
}
int main()
{
//for list
list<double> l; //creat a double type list
l.push_back(10); //pushing data into list l
l.push_front(11);//pushing data into list l
l.push_back(9);//pushing data into list l
l.push_front(12);//pushing data into list l
l.push_back(8);//pushing data into list l
list<double>::iterator itlist;
cout<<"Sum of List L is : "<< sum( itlist , l.begin() , l.end())<<endl;
}
我认为我做的不对。我有很多错误。我的错误之一是:
no instance of overloaded function "sum" matches the argument list -- argument types are: (std::_List_iterator<double>, std::_List_iterator<double>, std::_List_iterator<double>)
【问题讨论】:
-
您还没有告诉我们您遇到了什么问题。请将其添加到问题中。
-
请问
t是什么? -
代码没有编译,因为它给出了很多错误。我不认为我工作正常。
-
没有重载函数“sum”的实例与参数列表匹配——参数类型为:(std::_List_iterator
, std::_List_iterator , std::_List_iterator ) -
t是一个变量,而不是类型或命名空间。t::const_iterator没有意义。