【问题标题】:Best Fit memory allocation C++最佳拟合内存分配 C++
【发布时间】:2015-01-26 10:19:31
【问题描述】:

我想创建一个最合适的内存分配解决方案。

int main()
{
    int input;
    int memoryBlock[ARRAY_SIZE] = {5, 10, 3, 9, 7};
    int bestFit;

    cout << "Please enter the memory size you want to allocate: ";
    cin >> input;

    for (int i = 0; i < ARRAY_SIZE; i++){

        if (memoryBlock[i] - input < 0 ){

        }
        else {
            bestFit = memoryBlock[i];
        }

    }
    cout << bestFit;
}

基于上面的代码,我如何修改它以使else {} 选择最接近它的数字?

提前致谢。

【问题讨论】:

    标签: c++ memory allocation


    【解决方案1】:

    更改您的代码,使其仅在 bestFit 小于更好时替换它:

    int bestFit = -1;
    
    for (int i = 0; i < ARRAY_SIZE; ++i) {
        if (memoryBlock[i] - input >= 0 && memoryBlock[i] < bestFit) {
            bestFit = memoryBlock[i];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      相关资源
      最近更新 更多