使其正确通用:
#include <limits>
#include <vector>
template <typename C, typename T = typename C::value_type>
std::vector<unsigned> histogram(C const& container)
{
std::vector<unsigned> result(std::numeric_limits<T>::max() - std::numeric_limits<T>::min());
for(auto& el : container)
result[el - std::numeric_limits<T>::min()]++;
return result;
}
T
现在,对于大元素类型(无论输入长度如何),这将导致无用的大结果向量。考虑使用地图:
// for very large char types, consider
#include <map>
template <typename C, typename T = typename C::value_type>
std::map<T, unsigned> histogram_ex(C const& container)
{
std::map<T, unsigned> result;
for(auto& el : container)
result[el]++;
return result;
}
一些使用演示:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
auto v = histogram (std::string ("hello world"));
auto m = histogram_ex(std::wstring(L"hello world"));
std::wcout << L"Sum of frequencies: " << std::accumulate(v.begin(), v.end(), 0) << "\n";
for (auto p : m)
std::wcout << L"'" << p.first << L"': " << p.second << L'\n';
}
印刷:
Sum of frequencies: 11
' ': 1
'd': 1
'e': 1
'h': 1
'l': 3
'o': 2
'r': 1
'w': 1
在 Coliru 上看到这一切