std::valarray<T>::apply
valarray<T> apply( T func(T) ) const; | ||
valarray<T> apply( T func(const T&) ) const; |
Returns a new valarray of the same size with values which are acquired by applying function func
to the previous values of the elements.
Parameters
func | - | function to apply to the values |
Return value
The resulting valarray with values acquired by applying function func
.
Notes
The function can be implemented with the return type different from std::valarray
. In this case, the replacement type has the following properties:
- All
const
member functions ofstd::valarray
are provided. -
std::valarray
,std::slice_array
,std::gslice_array
,std::mask_array
andstd::indirect_array
can be constructed from the replacement type. - All functions accepting an argument of type
const std::valarray&
exceptbegin()
andend()
(since C++11) should also accept the replacement type. - All functions accepting two arguments of type
const std::valarray&
should accept every combination ofconst std::valarray&
and the replacement type. - The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
Example
calculates and prints the first 10 factorials.
#include <iostream> #include <valarray> #include <cmath> int main() { std::valarray<int> v = {1,2,3,4,5,6,7,8,9,10}; v = v.apply([](int n)->int { return std::round(std::tgamma(n+1)); }); for(auto n : v) { std::cout << n << ' '; } std::cout << '\n'; }
Output:
1 2 6 24 120 720 5040 40320 362880 3628800
See also
applies a function to a range of elements (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/numeric/valarray/apply