【问题标题】:No matching function call when passing iterators as arguments将迭代器作为参数传递时没有匹配的函数调用
【发布时间】:2017-07-17 15:17:56
【问题描述】:

我想创建一个 Sum() 函数来计算 STL 容器的总和。该函数使用模板参数作为迭代器类型,并接受两个迭代器作为参数,如下所示:

template <typename T>
double Sum(typename T::const_iterator start, typename T::const_iterator end)
{
    typename T::const_iterator i3;
    double sum2=0.0;
    for (i3=start; i3 != end; ++i3)
    {
        sum2 += (i3);
    }
    return sum2;
}

在 main() 中,我调用如下函数:

vector<double>::const_iterator vec_start=myvector.begin();
vector<double>::const_iterator vec_end=myvector.end();
cout<<"The sum of the vector is "<<Sum(vec_start, vec_end)<<endl;

但它说没有匹配的函数调用 Sum()。我阅读了一些讨论,这是因为函数签名是 T 但我传递了迭代器,并且我需要在传递迭代器参数之前指定数据类型。

【问题讨论】:

  • 有什么反对 std::accumulate 的理由吗?
  • 不只是练习容器迭代器的功课。

标签: c++ templates stl iterator containers


【解决方案1】:

正如您发现的讨论所说,模板参数T由于non-deduced contexts而无法自动推导,因此您需要明确指定它。例如

cout << "The sum of the vector is " << Sum<vector<double>>(vec_start, vec_end) << endl;
//                                        ~~~~~~~~~~~~~~~~

但其实你不需要这样做,你可以将Sum的声明改为:

template <typename I>
double Sum(I start, I end)
{
    I i3;
    double sum2=0.0;
    for (i3=start; i3 != end; ++i3)
    {
        sum2 += *i3;
    }
    return sum2;
}

I可以推导出来就可以了

cout << "The sum of the vector is " << Sum(vec_start, vec_end) << endl;

【讨论】:

  • 感谢您的回复!我现在看到了逻辑:)
  • 你的意思是*i3而不是(i3)吗?迭代器通常被取消引用以获得它所引用的值。
猜你喜欢
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 2023-04-02
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
相关资源
最近更新 更多