Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c++ - Correct implementation of min

At time 0:43:15 in this Tech-Talk about D, The implementation of the min function is discussed. Concerns about "stability" and "extra shuffling (if values are equal)" when being used in some algorithm(s) is proposed as one of the reasons for the implementation shown.

Can anyone provide a real/practical use-case (or provide a more detailed explanation) where this specific implementation of min is "stable" (aka better) as opposed to its other possible implementation? Or is this just another example of alpha-geeks going a bit too far?

Recommended implementation:

template <class LHS, class RHS, class Return>
inline Return min(LHS& lhs, RHS& rhs)
{
   return (rhs < lhs) ? rhs : lhs;
}

Other possible implementation:

template <class LHS, class RHS, class Return>
inline Return min(LHS& lhs, RHS& rhs)
{
   return (lhs < rhs) ? lhs: rhs;
}

Proposal N2199 provides implementations that are based on the latter, please note that the proposal was not successful at this time.

Other relevant proposals relating to min/max are N1840, N2485 and N2551

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this case, I'm pretty sure "stable" is referring to stable as it's applied in sorting -- i.e., that when/if two elements are equal, they stay sorted in the same order as they were to start with. To accomplish that, you want to return lhs when it's less than or equal to rhs -- but in C++ you (normally) want to do that using only operator<, without depending on having operator<=.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...