#include <iostream>
#include <vector>
namespace std17
{
template<class InputIt>
typename std::iterator_traits<InputIt>::value_type
reduce(InputIt first, InputIt last)
{
std::iterator_traits<InputIt>::value_type sum =
std::iterator_traits<InputIt>::value_type();
for (auto iter = first; iter != last; iter++)
{
sum = sum + *iter;
}
return sum;
}
}
int main()
{
std::vector<int> myInputVector{1, 2, 3, 4, 5};
int result;
result = std17::reduce(myInputVector.begin() ,
myInputVector.end() );
std::cout << result << " ";
std::cout << std::endl;
return 0;
}
// Output: 15
Reference: http://en.cppreference.com/w/cpp/algorithm/reduce
Monday, November 6, 2017
C++17: std::reduce()
C++17 added std::reduce(), which applies applies a binary operation on a range of elements. The default binary operation is addition. Here is an example (simulated with C++14):
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment