STL 用户定义的二进制操作
STL user defined binary operations
我一直在阅读有关STL的信息,并发现了以下代码:
int MyFunction(int total, int value)
{
return total + value * value;
}
int main()
{
vector<int> integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int result = accumulate(integers.begin(), integers.end(), 0, MyFunction);
cout << result;
}
我的问题是:累积如何将参数传递给MyFunction
。我的意思是:函数如何分配total
和value
值? 我想答案一定是我错过的简单东西,但我对此真的很困惑。提前谢谢。
考虑以下可能的std::accumulate()
实现:
template<class InputIt, class T, class BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op)
{
for (; first != last; ++first) {
init = op(init, *first); // <-- the call
}
return init;
}
您感兴趣的部分是op(init, *first)
.由于您将MyFunction
作为第四个参数传递给对std::accumulate()
函数模板的调用:
int MyFunction(int total, int value)
{
return total + value * value;
}
然后,在您的情况下,op
将被推断为类型int(*)(int, int)
(即,指向一个函数的指针,该函数取两个int
并返回int
(。此指针指向您的函数MyFunction()
。因此,基本上,std::accumulate()
分别将init
和*first
作为调用MyFunction()
的第一个和第二个参数传递。
看看 cpp偏好:
https://en.cppreference.com/w/cpp/algorithm/accumulate
template<class InputIt, class T, class BinaryOperation>
constexpr // since C++20
T accumulate(InputIt first, InputIt last, T init,
BinaryOperation op)
{
for (; first != last; ++first) {
init = op(std::move(init), *first); // std::move since C++20
}
return init;
}
应该明确发生了什么
std::accumulate
总是传递固定数量的参数,因此它知道如何调用你的函数,因为如果它采用不同数量的参数,代码将无法编译。 至于如何实现,cppreference有一些很好的例子 - https://en.cppreference.com/w/cpp/algorithm/accumulate - 例如:
template<class InputIt, class T>
constexpr // since C++20
T accumulate(InputIt first, InputIt last, T
init)
{
for (; first != last; ++first) {
init = std::move(init) + *first; // std::move since C++20
}
return init;
}
相关文章:
- STL 用户定义的二进制操作
- C++二进制文件 I/O 操作速度变慢.数据库如何处理二进制文件?
- 二进制模式 + 格式化文本操作或文本模式 + 二进制数据操作 - 有意义吗?
- 二进制搜索树操作程序错误:分割故障(核心倾倒)
- 如何在我的进程中运行的二进制文件中注册操作和内核
- 为什么C++标准指定有符号整数在具有混合符号的二进制操作中强制转换为无符号整数
- 重载二进制操作的正确方法
- 无效操作数以二进制读取结构的阵列
- 了解C++位操作中的二进制转换实现
- "constexpr"通过二进制操作减少"std::array"
- 警告 639:二进制操作中类型 'uint64' 的强类型不匹配
- 二进制搜索操作
- 二进制与文本模式下的文件操作 -- 性能问题
- 如何在C++中操作和表示二进制数
- 重新创建具有最少"XOR"操作的二进制矩阵
- GDB 不会执行二进制操作
- 如何在两个容器的元素之间执行成对二进制操作?
- 二进制操作的示例程序
- 在c++中将包含二进制操作的字符串转换为双精度类型
- 十六进制和二进制操作