Here is my first try at a generic histogram template function in C++ tested with GCC 4.6. However, I would like to merge dense_histogram() and sparse_histogram() into one common generic function template. The problem is that the dense-specific constructor H h(n, 0) is neither defined nor relevant in the sparse version H h. Is there a way to solve this in some clever C++ regular way or statically typically using conditional compilation through Boost Type.Traits (#include <boost/type_traits.hpp>)?
#include <algorithm>
#include <limits>
#include <algorithm>
#include <vector>
#include <unordered_map>
namespace std
{
/*!
* \em Dense Histogram of \p a.
*
* \tparam V is Value Type.
* \tparam C is Count (Bin) Type.
* \tparam H is Histogram Storage Type, typically a vector.
*
* \param[in] x is a set of the input data set
*/
template <class V, class C = size_t, class H = vector<C> >
inline
H dense_histogram(const V & x)
{
typedef typename V::value_type E; // element type
size_t n = (static_cast<C>(1)) << (8*sizeof(E)); // maximum number of possible elements for dense variant
H h(n, 0); // histogram
C bmax = 0; // bin max
for_each(begin(x), end(x), // C++11
[&h, &bmax] (const E & e) { // value element
h[e]++;
bmax = std::max(bmax, h[e]);
});
return h;
}
template <class V, class H = vector<size_t> > H make_dense_histogram(const V & x) { return dense_histogram<V, size_t, H>(x); }
/*!
* \em Sparse Histogram of \p a.
*
* \tparam V is Value Type.
* \tparam C is Count (Bin) Type.
* \tparam H is Histogram Structure Type, typically a unordered_map.
*
* \param[in] x is a set of the input data set
*/
template <class V, class C = size_t, class H = unordered_map<typename V::value_type, C> >
inline
H sparse_histogram(const V & x)
{
typedef typename V::value_type E; // element type
H h; // histogram
C bmax = 0; // bin max
for_each(begin(x), end(x), // C++11
[&h,&bmax] (const E & e) { // value element
h[e]++;
bmax = std::max(bmax, h[e]);
});
return h;
}
template <class V, class H = unordered_map<typename V::value_type, size_t> > H make_sparse_histogram(const V & x) { return sparse_histogram<V, size_t, H>(x); }
}
run using
I think you should simply put only the common parts in a third function leaving
dense_histogramandsparse_histogramto createhand call that implementation function:However since you asked for it: As you are working on containers I would assume they have a cheap move, so you could define a creation trait to generate your container and move that into your local variable. Then you can write your own detection of an appropriate constructor like this:
As a side not: Adding your own methods to
stdis UB by the standard ([namespace.std] $17.6.4.2.1 p1):