在模板中奇怪地使用 std::累积

Odd use of std::accumulate in a template

本文关键字:std 累积      更新时间:2023-10-16

我在旧版本的C++食谱中看到过这段代码,它让我感到困惑。这似乎是编译的,但我不知道为什么代码会这样写。

T(( 是什么意思?这是 std::accumulate 的 init 参数 -- 开始求和的值。我写了一个版本,我用double((代替T(((以"硬连线"模板(,然后它就可以编译了。double(( 是什么意思?

#include <iostream>
#include <numeric> // accumulate
#include <vector>
template<class T, class Iter_T>
void computeAccum(Iter_T first, Iter_T last, T& accum)
{
accum = std::accumulate(first, last, T()); // Why is init argument equal to T()?
}
int main()
{
std::vector<double> vd;
vd.push_back(1.11);
vd.push_back(2.22);
vd.push_back(4.44);
vd.push_back(3.33);
double sum1;
std::cout << "Here is the vector:" << std::endl;
std::vector<double> ::iterator it;
for (it = vd.begin(); it != vd.end(); ++it) {
std::cout << *it << std::endl;
}
computeAccum2(vd.begin(), vd.end(), sum1);
std::cout << "Answer: " << sum1 << std::endl;
}

累加器的这个变体有三个参数,范围中的第一个和最后一个元素,以及要开始的初始值(下面的这个特定原型是C++20,尽管早期的原型相似,只是constexpr优点较低(:

template< class InputIt, class T >
constexpr T accumulate( InputIt first, InputIt last, T init );

它允许您积累到已经开始的事情。所以如果你34累积值,初始值为22,最终值将是28。这样做的原因是您可能希望积累一组特定的数据,然后再积累更多数据。通过使用初始起始值,您可以将多个累积到单个项目中。

在这种情况下,T()只是模板类型的默认构造初始元素,基本上是您使用的任何类型的"零"值。

它基本上是零初始化。为了澄清起见,请考虑此示例

#include <bits/stdc++.h> 
using namespace std;
int main(){
cout<<"Int: "<<int()<<endl;
cout<<"Float: "<<float()<<endl;
cout<<"String: "<<string();
}

输出:

Int: 0
Float: 0
String: