C++ std::reduce 与数组
C++ std::reduce with array
int arr1[5] = { 1,2,3,4,5 };
int sum = reduce(arr1[0], arr1[5]);
我编写此代码是为了将 std::reduce
函数与整数数组一起使用。我应该如何定义数组的开头和结尾?
在数组上使用 std::cbegin()
and std::cend()
:
#include <iostream>
#include <numeric>
int main(){
int arr1[5] = { 1,2,3,4,5 };
int sum = std::reduce(std::cbegin(arr1), std::cend(arr1));
std::cout << sum;
}
如果你经常在容器上使用 <algorithm>
算法,你可以这样写:
template <typename Container>
constexpr typename Container::value_type
reduce(const Container& container) {
return std::reduce(std::cbegin(container), std::cend(container));
}
那么你可以:
int arr1[5] = { 1,2,3,4,5 };
auto sum = reduce(arr1);
这有几个缺点,包括:
- 只是其中之一 several variants of
std::reduce()
- 尽管您当然可以实现更多。
- 它在全局命名空间中(但您可以将其放在您自己的命名空间中,例如
util
或 stdx
)。
- 不去“std-ranges way" (see also Ranges library (C++20)).
PS - 正如@Ben 指出的那样,Boost 库 have 此类容器适配器适用于大多数 <algorithm>
功能......但不适用于 std::reduce
.
int arr1[5] = { 1,2,3,4,5 };
int sum = reduce(arr1[0], arr1[5]);
我编写此代码是为了将 std::reduce
函数与整数数组一起使用。我应该如何定义数组的开头和结尾?
在数组上使用 std::cbegin()
and std::cend()
:
#include <iostream>
#include <numeric>
int main(){
int arr1[5] = { 1,2,3,4,5 };
int sum = std::reduce(std::cbegin(arr1), std::cend(arr1));
std::cout << sum;
}
如果你经常在容器上使用 <algorithm>
算法,你可以这样写:
template <typename Container>
constexpr typename Container::value_type
reduce(const Container& container) {
return std::reduce(std::cbegin(container), std::cend(container));
}
那么你可以:
int arr1[5] = { 1,2,3,4,5 };
auto sum = reduce(arr1);
这有几个缺点,包括:
- 只是其中之一 several variants of
std::reduce()
- 尽管您当然可以实现更多。 - 它在全局命名空间中(但您可以将其放在您自己的命名空间中,例如
util
或stdx
)。 - 不去“std-ranges way" (see also Ranges library (C++20)).
PS - 正如@Ben 指出的那样,Boost 库 have 此类容器适配器适用于大多数 <algorithm>
功能......但不适用于 std::reduce
.