std::multiplies
Prerequisites
1. What is std::multiplies?
std::multiplies is a function object (functor) defined in <functional> that performs multiplication.
It is part of the standard functional utilities used with STL algorithms.
1
2
3
4
5
| #include <functional>
std::multiplies<int> mul;
int result = mul(3, 4); // 12
|
Key Idea
1
| std::multiplies<T>()(a, b) == a * b
|
behaves like a function:
1
| int x = std::multiplies<int>()(3, 4); // 12
|
2. Function Signature
1
2
3
4
5
| template<class T>
struct multiplies
{
constexpr T operator()(const T& lhs, const T& rhs) const;
};
|
Example with std::accumulate
1
2
3
4
5
6
7
8
9
| #include <numeric>
#include <functional>
#include <vector>
std::vector<int> v = {1, 2, 3, 4};
int product = std::accumulate(v.begin(), v.end(),
1,
std::multiplies<>());
|
Example with std::reduce
1
2
3
4
5
6
7
8
| #include <numeric>
#include <execution>
#include <functional>
int product = std::reduce(std::execution::par,
v.begin(), v.end(),
1,
std::multiplies<>());
|
3. Why Use std::multiplies
Cleaner Code
1
2
3
4
5
| std::accumulate(v.begin(), v.end(), 1,
[](int a, int b)
{
return a * b;
});
|
vs
1
| std::accumulate(v.begin(), v.end(), 1, std::multiplies<>());
|
shorter and clearer
Generic Programming
Works well in templates:
1
2
3
4
5
| template<typename T>
T product(const std::vector<T>& v)
{
return std::accumulate(v.begin(), v.end(), T{1}, std::multiplies<>());
}
|
Works with Parallel Algorithms
cpp id="ck8u0p" std::reduce(std::execution::par, v.begin(), v.end(), 1, std::multiplies<>());
associative operation → safe for parallel
| Functor | Operation |
|---|
std::plus | a + b |
std::minus | a - b |
std::multiplies | a * b |
std::divides | a / b |
std::modulus | a % b |