【问题标题】:How to use 2 iterators for sum function calculating map <string, double>如何使用 2 个迭代器进行求和函数计算 map <string, double>
【发布时间】:2017-04-15 14:07:10
【问题描述】:

我正在研究一个关于 STL 迭代器的问题,问题是:创建一个 Sum() 函数来计算两个迭代器之间的总和。

template<class T1, class T2 >
double Sum<T1,T2>(map<T1,T2>& start, map<T1,T2>&end)   
{
    double sum = 0.0;
   class map<T1,T2>::const_iterator i;
    for (i = start; i != end; ++i)
    {
        sum += i->second;
    } 
    return sum;
}

下面是我的 main() 中的内容:

map<string, double>::const_iterator map_StartIter =doubleMap.begin();   
map<string, double>::const_iterator map_EndIter = doubleMap.end();
cout<<"(2 iterator) map Sum is "<< Sum(map_StartIter,map_EndIter) << endl;

它抛出一个错误,提示错误 C2768: 'Sum' : 非法使用显式模板参数

出了什么问题?

【问题讨论】:

    标签: c++ templates dictionary stl iterator


    【解决方案1】:

    应该是这样的:

    template<class Iter >
    double Sum(Iter begin, Iter end)
    {
         double sum = 0;
         for( Iter it = begin; it != end; ++it )
             sum += it->second;
         return sum;
    }
    

    注意如果你需要计算map &lt;string, double&gt;,你不必使用模板,你可以指定具体的类型。

    【讨论】:

    • 相当肯定模板参数不能在这里推导,所以const_iterators必须显式传入。天真地从可变映射传入begin()end()会失败。
    【解决方案2】:

    您遇到的具体错误是您不应在其声明中的函数名称旁边再次指定模板参数:

    template<class T1, class T2 >
    double Sum<T1,T2>(map<T1,T2>& start, map<T1,T2>&end) 
              ^~~~~~~
    

    如果您删除了突出显示的部分,您将遇到下一个问题,即您接受两个映射而不是它们的迭代器:

    template <class T1, class T2>
    double Sum(typename std::map<T1, T2>::const_iterator it,
               typename std::map<T1, T2>::const_iterator end)
    {
        double sum = 0.0;
        for (; it != end; ++it)
        {
            sum += it->second;
        } 
        return sum;
    }
    

    注意:内部变量是不必要的,因为您应该通过复制获取迭代器。

    然而,这是非惯用代码:它真的很冗长,并且会阻止您通过 std::unordered_mapstd::multimap (例如)传递迭代器。

    相反,您可以简单地再上一层,并使用 迭代器类型 本身作为模板参数:

    template <typename I>
    double Sum(I it, I end)
    {
        double sum = 0.0;
        for (; it != end; ++it)
        {
            sum += it->second;
        } 
        return sum;
    }
    

    最后,Sum 函数的结果类型不适用于包含 int64_t 的映射。您可以改为使用迭代器的内部 value_type 来获取类型...但它很冗长,而使用 decltype 通常更简单:

    template <typename I>
    auto Sum(I it, I end) -> decltype(it->second)
    {
        decltype(it->second) sum = 0;
        for (; it != end; ++it)
        {
            sum += it->second;
        } 
        return sum;
    }
    

    这样,当你添加整数时,你会得到一个整数。

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2015-12-05
      • 2019-05-24
      • 1970-01-01
      相关资源
      最近更新 更多