这是一个未经测试的通用算法,它采用任意长度 M 的输入向量和 N-1 个 bin 边界的排序向量,并返回 N 个 bin 计数的向量。Bin i 计算区间 [breaks[i-1], breaks[i]) 中的值。T1 和 T2 类型应该是相互可比的。复杂度等于 O(M * log (N))。
#include<algorithm> // std::is_sorted, std::lower_bound
#include<cassert> // assert
#include<iterator> // std::distance
#include<vector> // std::vector
template<typename T1, typename T2>
std::vector<std::size_t> bin_count(const std::vector<T1>& input, const std::vector<T2>& breaks)
{
// breaks is a sorted vector -INF < a0 < a1 < ... < aN-2 < +INF
assert(std::is_sorted(breaks.begin(), breaks.end()));
auto N = breaks.size() + 1;
std::vector<std::size_t> output(N, 0);
if (N == 1) {
// everything is inside [-INF, INF)
output[0] = input.size();
return output;
}
for(auto it = input.begin(), it != input.end(); ++it) {
if (*it < breaks.front()) {
// first bin counts values in [-INF, a0)
++output[0];
break;
}
if (*it >= breaks.back()) {
// last bin counts values in [aN-1, +INF)
++output[N-1];
break;
}
const auto break_it = std::lower_bound(breaks.begin(), breaks.end(), *it);
bin_index = std::distance(breaks.begin(), break_it) + 1;
++output[bin_index];
}
return output;
}