在模板中奇怪地使用 std::累积
Odd use of std::accumulate in a template
我在旧版本的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 );
它允许您积累到已经开始的事情。所以如果你3
和4
累积值,初始值为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:
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何使用 std::累积在 C++ 中计算总和立方体
- 我可以将向量作为initial_sum和不同的函数传递给 std::累积吗?
- 在模板中奇怪地使用 std::累积
- 无法编译 std::reduce 调用,而 std::累积调用编译相同的参数
- std::transform 可以替换为 std::累积吗?
- 我可以毫无例外地使用 std::累积与易错操作吗?
- 当调用时,为什么ranges ::累积的init as std :: Move(init)
- 如何将对象传递到std ::累积函数
- 将异步与std ::累积
- 可能溢出 std::累积
- TBB :: Parallel_Reduce和STD ::累积的结果不同
- 是否有类似STD ::累积在迭代器上运行的东西
- 如何使用 std::累积 和 lambda 来计算平均值
- 在std::for_each的执行过程中累积结果,该异常被中断
- std::累积BinaryOperator副作用
- 使用 std::累积,得到一个"too many arguments"错误