首页 > 解决方案 > 如何将向量的值分布在“桶”中而不超出边界?

问题描述

我决定尝试编写桶排序。我开始这样的标准方式:

template <typename T>
void Bucket_sort(T& container) {
    std::size_t count_bucket = std::sqrt(std::size(container));
    auto max = *std::max_element(std::begin(container), std::end(container));
    auto min = *std::min_element(std::begin(container), std::end(container));
    auto range = (max - min) / (count_bucket);
    std::vector<T> bucket(count_bucket);
    for (auto curr : container) {
        std::size_t bucket_index = (curr - min) / range;
        bucket[bucket_index].push_back(curr);
    }  
}

但我无法正确获取索引。比方说,我有一个大小为 10 的向量

std::vector<int> for_sort(10);

因此std::size_t count_bucket = std::sqrt(std::size(container));它等于3。接下来,我计算range然后在计算时超出范围bucket_index。获得值 3(在计算最大值的 idex 时),因此会出现错误。有人能建议如何最好地避免这种情况吗?

标签: c++

解决方案


推荐阅读