• 内存分配 A


     

     

     思路:定义全局变量数组保存,通过map映射。

    #include <iostream>
    #include <string>
    #include <map>
    using namespace std;
    
    class MiniMemoryPool {
    private:
        int total[100] = {0};
        int totalmem = 100;
        map<int, int> mem;
    public:
    
        bool isempty(int s, int size) {
            for (int i = 0; i < size; i++) {
                if (total[s + i]) {
                    return false;
                }
            }
            return true;
        }
        // 返回分配的内存首地址,失败返回 -1
        int Request(int size)
        {
            if (size == 0 || size > totalmem) {
                return -1;
            } else {
                for (int i = 0; i < 100; i++) {
                    if (isempty(i, size)) {
                            totalmem -= size;
                            mem[i] = size;
                            for(int k = 0; k < size;k++) {
                                total[k+i] = 1;
                            }
                            return i;
                        }
                }
            }
            return -1;
        }
    
        // 释放内存地址, 成功返回 true, 失败返回 false
        bool Release(int startAddr)
        {
            if (mem[startAddr]) {
                totalmem += mem[startAddr];
                for (int i = 0; i < mem[startAddr]; i++) {
                    total[i + startAddr] = 0;
                }
                mem.erase(startAddr);
                return true;
            }
            return false;
        }
    };
    
    int main()
    {
        int num;
        cin >> num;
    
        MiniMemoryPool pool;
        for (int loop = 0; loop < num; loop++) {
            string line;
            cin >> line;
    
            string commond = line.substr(0, line.find_first_of('='));
            if (commond == "REQUEST") {
                int size = stoi(line.substr(line.find_first_of('=')+1));
                int result = pool.Request(size);
                if (result != -1) {
                    cout << result << endl;
                } else {
                    cout << "error" << endl;
                }
            } else if (commond == "RELEASE") {
                int addr = stoi(line.substr(line.find_first_of('=')+1));
                if (!pool.Release(addr)) {
                    cout << "error" << endl;
                }
            }
        }
    
        return 0;
    }
  • 相关阅读:
    帧框架总结
    Java中Excel表格的上传与下载
    一种解决eclipse中安装maven出错的方法
    Eclipse中如何忽略报错的js文件
    如何解决jQuery easyui中locale文件下easyui-lang-zh_CN中文乱码问题
    java面试题
    登录功能(MD5加密)
    CSS基础
    java框架之spring
    基于Docker搭建Maven私服环境
  • 原文地址:https://www.cnblogs.com/gcter/p/15898302.html
Copyright © 2020-2023  润新知