0

我只是想创建一个简单的 sum 函数模板来使用 STL 在容器中查找双精度数的总和。首先,我只是想用一个列表来测试它,但我在第 28 行不断收到错误消息。

#include <iterator>
#include <list>    
#include <iostream>

using namespace std;

template <typename T>
double Sum(typename T& container)
{// sum of a container with doubles
    typename T::const_iterator iterator_begin = container.begin();
    typename T::const_iterator iterator_end = container.end();

    double my_sum = 0;

    for (iterator_begin; iterator_begin != iterator_end; iterator_begin++)
        my_sum += iterator_begin->second; // this is line 28

        return my_sum;
}

int main()
{
    list<double> test_list(10,5.1); // create a list of size 10 with values 5.1

    cout << Sum(test_list) << endl;

    return 0;
}

我得到两个编译器错误:

c:\users...\iterators.cpp(28): 错误 C2839: 重载 'operator ->' 的返回类型 'const double *' 无效

c:\users...\iterators.cpp(28): error C2039: 'second' : is not a member of 'std::_List_const_iterator<_Mylist>'

即使我从 const_iterator 更改为 iterator,我仍然会收到类似的错误,

错误 C2839:重载的“运算符 ->”的返回类型“双 *”无效

我在这里使用错误的指针还是什么?谢谢!

4

1 回答 1

1

STL 列表不支持“第二”的概念。它们是简单的序列。这似乎最初是为 std::map<> 量身定制的。话虽如此,如果列表、向量、队列等是您的目标容器,那么:

改变这个:

my_sum += iterator_begin->second;

对此:

my_sum += *iterator_begin;

它会按照您显然想要的方式工作。在 STL(for_each 等)中有用于执行此类操作的内置算法,您应该将其视为潜在的替代方案。

编辑:OP 询问如何专门为简单序列和地图求和。

#include <iostream>
#include <list>
#include <map>

using namespace std;

// general summation
template<typename T>
double Sum(const T& container)
{
    double result = 0.0;
    typename T::const_iterator it = container.begin();
    while (it != container.end())
        result += *it++;
    return result;
}

// specialized for a map of something-to-double
template<typename Left>
double Sum(const map<Left,double>& themap)
{
    double result = 0.0;
    typename map<Left,double>::const_iterator it = themap.begin();
    while (it != themap.end())
        result += (it++)->second;
    return result;
}

// a list of doubles.
typedef list<double> DblList;

// a map of int to double
typedef map<int, double> MapIntToDbl;

// and just for kicks, a map of strings to doubles.
typedef map<string, double> MapStrToDbl;


int main(int argc, char** argv)
{
    DblList dbls;
    dbls.push_back(1.0);
    dbls.push_back(2.0);
    dbls.push_back(3.0);
    dbls.push_back(4.0);
    cout << "Sum(dbls) = " << Sum(dbls) << endl;

    MapIntToDbl mapdbls;
    mapdbls[1] = 1.0;
    mapdbls[2] = 2.0;
    mapdbls[3] = 3.0;
    mapdbls[4] = 4.0;
    mapdbls[5] = 5.0;
    cout << "Sum(mapdbls) = " << Sum(mapdbls) << endl;

    MapStrToDbl mapdbls2;
    mapdbls2["this"] = 1.0;
    mapdbls2["is"] = 2.0;
    mapdbls2["another"] = 3.0;
    mapdbls2["map"] = 4.0;
    mapdbls2["sample"] = 5.0;
    cout << "Sum(mapdbls2) = " << Sum(mapdbls2) << endl;

    return 0;
}
于 2012-09-30T18:47:25.330 回答