计算STL容器中两个迭代器之间的和

Calculate the sum between two iterators in STL containers

我正在处理 STL 容器中的一个问题:

创建一个 Sum() 函数来计算两个迭代器之间的总和。然后该函数使用迭代器类型的模板参数并接受两个迭代器,开始和结束

我正在尝试编写以下代码,但我不明白这个问题,请问谁能帮助我。

template <typename type , typename start , typename  end>
double sum(type& t, start& s , end& e) 
{
  typename t::const_iterator i;
  double sum = 0;
  for (i = s  ; i != e; ++i)
    {
      sum+=*i;
    }
  return sum;
}


int main()
{
  //for list 
  list<double> l; //creat a double type list
  l.push_back(10); //pushing data into list l
  l.push_front(11);//pushing data into list l
  l.push_back(9);//pushing data into list l
  l.push_front(12);//pushing data into list l
  l.push_back(8);//pushing data into list l
  list<double>::iterator itlist;

   cout<<"Sum of List L is : "<< sum( itlist , l.begin() , l.end())<<endl;
}

我认为我做的不对。我有很多错误。我的错误之一是:

no instance of overloaded function "sum" matches the argument list -- argument types are: (std::_List_iterator<double>, std::_List_iterator<double>, std::_List_iterator<double>)

您的代码存在许多问题。在这个函数中:

template <typename type , typename start , typename  end>
double sum(type& t, start& s , end& e) 

您正在引用 se。但这不能绑定到 l.begin()l.end(),因为它们 return r-values.

迭代器通常通过复制传递,所以你可以简单地写:

template <typename type , typename start , typename  end>
double sum(type& t, start s , end e) 

你这里也有问题:

typename t::const_iterator i;

你不能这样做,因为 t 是一个变量,而不是类型。

但是,您根本不需要拼出 i 的类型。相反,您可以简单地写:

for (auto i = s  ; i != e; ++i)
{
  // ...
}

并让编译器推断出 i.

的类型

事实上,根本不需要将 itlist 传递给您的函数,因为所有需要的信息都在其他参数中。此外,由于两个参数具有相同的类型,因此您只需要一个模板参数。

所以现在你的函数就是

template <typename iter>    // a single template argument
double sum(iter s , iter e) // 2 function arguments, both of the same type
{
  // ...
}

你会这样称呼它:

sum(l.begin() , l.end())

这是一个demo

您可以尝试的一种方法是将 const 引用传递给迭代器的开始和结束。而且,一个typename就够了,你可以舍弃其他的。

那么这个typename t::const_iterator i;就没有意义了,因为t是一个变量。要回答您的评论,您也不能 typename type::const_iterator i;

最简单的解决方案是丢弃 const 迭代器中有问题的那一行,并在 for 循环中使用 auto 关键字。

将所有内容放在一起,您会得到:

template <typename T>
double sum(T const& start, T const& end) 
{
  double sum = 0;
  for(auto i = start; i != end; ++i)
  {
    sum+=*i;
  }
  return sum;
}

这样调用的:

cout << "Sum of List L is: "<< sum(l.begin() , l.end()) << endl;

并输出 (Run it Online):

Sum of List L is: 50

备选方案:@cigien 的回答,它通过值而不是引用传递迭代器,这是传递迭代器的典型方法 - 我只是想尽可能接近 OP 的代码。


回答您的评论:

Create a Sum() function that calculates the sum between two iterators. The function then uses the template argument for the iterator type and accepts two iterators, the start and the end.

那么您可以简单地使用类型名称 T 而不是 auto 关键字,如下所示:

template <typename T>
double sum(T const& start,T const& end) 
{
  double sum = 0;
  for(T i = start; i != end; ++i)
  {
    sum+=*i;
  }
  return sum;
}

Run it Online