This function finds the [min, max] of a container based on the definition of “smaller”.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<algorithm>
#include<vector>
#include<iostream>intmain(){std::vector<int>vec={3,1,4,1,5,9,2,6,5,3,5};autominmax=std::minmax_element(vec.begin(),vec.end(),[](constint&i1,constint&i2){returni1<i2;// return i1>i2; // the first element (min) is the one that satisfies this condition throughout the container});// See Min element: 1std::cout<<"Min element: "<<*minmax.first<<std::endl;std::cout<<"Max element: "<<*minmax.second<<std::endl;return0;}
std::min_element: returns the min element based on the defintion of “smaller”
std::min(v1, v2)
std::transform
std::transform is a funtion that allows us to apply a function (usually lambda) on one or two (zipped) containers, and puts the output into an output container.
unary operations
1
2
3
4
5
6
7
// Definitiontransform(IteratorinputBegin,IteratorinputEnd,IteratorOutputBegin,unary_operation)// example: increment a number in an arrayintarr[]={1,2,3,4};n=sizeof(arr)/sizeof(int);std::transform(arr,arr+n,arr,[](intx){returnx+1;})
std::reduce is an algorithm introduced in C++17 (and enhanced in C++20) that aggregates a range of elements using a binary operation and an initial value.
Unlike std::accumulate, std::reduce has no guaranteed order of evaluation, which allows it to be parallelized for improved performance. However, because it processes elements in an unspecified order, the binary operation should be both associative and commutative to guarantee correct results.
#include<optional>
#include<iostream>
#include<vector>
#include<numeric>usingnamespacestd;voidtest_reduce(){std::vector<int>vec{1,2,3,4,5};// order of execution is unspecifieddoublesum=std::reduce(std::execution::par_unseq,vec.begin(),vec.end(),0.0,[](inta,doublesum){return0.25*a+sum;});cout<<"using reduce to find sum: "<<sum<<endl;}intmain(){// test_optional();test_reduce();}
std::execution::par_unseq parallelizes the above.
Pay attention to the initial value 0.0, otherwise, it will be an int and will be rounded.
std::numeric_limits<float>::quiet_NaN(): propagates through arithmetic operations without triggering floating-point exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
floatnan_value=std::numeric_limits<float>::quiet_NaN();std::cout<<"NaN value: "<<nan_value<<std::endl;// Checking if a value is NaNif(std::isnan(nan_value)){std::cout<<"The value is NaN."<<std::endl;}// Propagation examplefloatresult=nan_value+5.0f;// Still NaNstd::cout<<"Result of NaN + 5: "<<result<<std::endl;
std::numeric_limits<T>::signaling_NaN: signaling NaN (SNaN) raises an exception when used in computations.