3

私はSTLとテンプレートを学んでいます。これが私の問題です。2 つのイテレータ「の間」の要素の合計を計算するこの関数を作成しました。

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は異なる働きをします。したがって、overloaded/specialized と書きたいと思います。私が試して失敗したのはこれです(最小限の例):std::vectorstd::listPartialSum

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;

とても単純なので、おそらく非常に基本的なことを理解していません。ご意見をお聞かせいただければ幸いです:-)

4

3 に答える 3