I want dLower
and dHigher
to have the lower and higher of two double values, respectively - i.e. to sort them if they are the wrong way around. The most immediate answer, it seems is:
void ascending(double& dFirst, double& dSecond)
{
if(dFirst > dSecond)
swap(dFirst,dSecond);
}
ascending(dFoo, dBar);
But it seems like such an obvious thing to do I wondered if I'm just not using the right terminology to find a standard routine.
Also, how would you make that generic?
This is a good way of approaching it. It is as efficient as you are going to get. I doubt that this specific function has a generally recognized name. This is apparently called comparison-swap.
Generalizing it on type is as easy as:
template <typename T>
void ascending(T& dFirst, T& dSecond)
{
if (dFirst > dSecond)
std::swap(dFirst, dSecond);
}
Corroborating this function:
int main() {
int a=10, b=5;
ascending(a, b);
std::cout << a << ", " << b << std::endl;
double c=7.2, d=3.1;
ascending(c, d);
std::cout << c << ", " << d << std::endl;
return 0;
}
This prints:
5, 10
3.1, 7.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With