c++ - 如何将向量的值分布在“桶”中而不超出边界?
问题描述
我决定尝试编写桶排序。我开始这样的标准方式:
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 时),因此会出现错误。有人能建议如何最好地避免这种情况吗?
解决方案
推荐阅读
- html - 从 Angular 组件绑定到 HTML 模板时,iframe 代码正在转换为 dom 对象
- c# - 告诉玩家何时强制在 Unity 中关闭游戏
- php - PDF 中的边框和值不匹配
- python - 为什么 np.nan 不是布尔值 True
- java - Big O. 不确定 for 循环上的更新如何影响它
- wmi - WMI 很慢
- javascript - Express 函数被多次调用
- java - 对于 PreparedStatement 类型,方法 getInt、getString 和 getDate 未定义
- swift - Swift 中的歧义引用
- c++ - 提高 SPI 传输速度