Correct implementation of min

旧时模样 提交于 2019-11-27 04:31:02

问题


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


回答1:


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<=.




回答2:


In general case there is no advantage to one implementation over the other. If you're implementing min for a specific usage, it might make sense to choose one of the forms based on the data to which it will be applied to make the most of branch predictions.

If for most usage cases the expected minimum is rhs, choose the first implementation. If it's lhs, choose the second implementation.



来源:https://stackoverflow.com/questions/4174447/correct-implementation-of-min

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!