我正在学习 STL 和模板。这是我的问题。我写了这个函数来计算两个迭代器“之间”的元素总和:
template <typename Iter> double PartialSum(Iter itBegin, Iter itEnd){
if (itBegin == itEnd) return 0.;
double dSum = 0;
while(itBegin != itEnd){
dSum += (*itBegin);
++itBegin;
}
return dSum;
}
这很好用(我知道我可以使用std::accumulate
,但这是出于学习目的)。现在,我希望具有相同的功能,std:map
但迭代器的工作方式与std::vector
and的情况不同std::list
。因此,我想写重载/专业PartialSum
。我尝试过但失败的是这个(最小的例子):
template <typename T1, typename T2> double PartialSum(std::map<T1,T2>::iterator itBegin{
return 0.;
}
这是错误日志:
Main.cpp(42): error: nontype "std::map<_Key, _Tp, _Compare, _Alloc>::iterator [with _Key=T1, _Tp=T2, _Compare=std::less<T1>, _Alloc=std::allocator<std::pair<const T1, T2>>]" is not a type name template <typename T1, typename T2> double PartialSum(std::map<T1,T2>::iterator itBegin){ Main.cpp(83): error: no instance of overloaded function "PartialSum" matches the argument list argument types are: (std::_Rb_tree_iterator<std::pair<const std::string, int>>) std::cout<<"Map partial sum: "<<PartialSum(myMap.begin())<<std::endl;
由于它是如此简单,我可能不会低估一些非常基本的东西。很高兴听到你的意见:-)