c++ - What can we return as an "NaN" when writing template algorithm for "most frequent value"? -


i write simple template function range-based , container-based search of "most frequent value", 'generic' i'm wondering should return if container or range empty. in 1st draft below used numeric_limits return quiet_nan or signaling_nan, if std::iterator_traits::value_type string ... default ctor idea or pratice ?

struct comp_by_second {   template <typename pair>   bool operator()(const pair& a, const pair& b)   {     return a.second < b.second;   } };  template <typename fwd> typename std::iterator_traits<fwd>::value_type  most_frequent_element(fwd begin, fwd end) { std::map<typename std::iterator_traits<fwd>::value_type, int> count; (fwd = begin; != end; ++it)   ++count[*it];  if(count.size() == 0) {   if(std::numeric_limits<typename std::iterator_traits<fwd>::value_type >::has_quiet_nan)     return std::numeric_limits<typename std::iterator_traits<fwd>::value_type>::quiet_nan();   else {     if(std::numeric_limits<typename std::iterator_traits<fwd>::value_type >::has_signaling_nan)       return std::numeric_limits<typename std::iterator_traits<fwd>::value_type>::signaling_nan();     else {       return std::iterator_traits<fwd>::value_type () /*default ctor similar uninitialized ... ??? */;     }   } } else    return (*std::max_element(count.begin(), count.end(), comp_by_second())).first; }  template <typename c> typename std::iterator_traits<typename c::iterator>::value_type  most_frequent_element(const c& container) {  return most_frequent_element(container.begin(), container.end()); } 

if allowed input range not cover possible values of data type (for example, if data type float , know nans not allowed), can choose such "non-allowed" value , return in case container empty.

however, if there no such non-allowed value, case generic template function, strategy impossible. note returning nan not quite correct, because can have container full of nans, why not?.. in case should use special way of returning "no value". boost::optional made for. in particular, see motivation discussion of different approaches.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -