c++ - 如何为动态数组实现 operator[]?

标签 c++ arrays dynamic-data

我需要自己实现一个动态数组,以便在一个简单的内存管理器中使用它。

struct Block {       
    int* offset;
    bool used;
    int size;
    Block(int* off=NULL, bool isUsed=false, int sz=0): offset(off), used(isUsed), size(sz) {}
    Block(const Block& b): offset(b.offset), used(b.used), size(b.size) {}
};

class BlockList {
    Block* first;
    int size;
public:
    BlockList(): first(NULL), size(0) {}
    void PushBack(const Block&);
    void DeleteBack();
    void PushMiddle(int, const Block&);
    void DeleteMiddle(int);
    int Size() const { return size; }
    void show();
    Block& operator[](int);
    Block* GetElem(int);
    void SetElem(int, const Block&);
    ~BlockList();
};

我需要重载operator[]

Block& BlockList::operator\[\](int index) {
    try {
        if (index >= size)
            throw out_of_range("index out of range");
        else 
            return (first[sizeof(Block)*index]);
    }
    catch(exception& e) {
        cerr << e.what() << endl;
    }
}

void BlockList::PushBack(const Block& b) {
    if(!size) 
        first = new Block(b);
    else {
        Block* temp = new Block[size + 1];
        int i = 0;
        for (i = 0; i < size; i++) 
            temp[sizeof(Block)*i] = this->operator[](i);
        delete []first;
        temp += sizeof(Block);
        temp->offset = b.offset;
        temp->size = b.size;
        temp->used = b.used;
        first = temp;
    }
    size++;
}

当我使用 PushBack 推送第一个元素时,它工作正常,但是当涉及到第二个,第三个......时,程序没有崩溃,但它只是显示结果我没想到会看到。

这是我获取数组内容的方法:

void BlockList::show() {
    for (int i = 0; i < size; i++) {
        Block current(operator[](i));
        cout << "off: " << current.offset << " size: " << current.size << endl;
    }
}

最佳答案

first 是一个Block 指针,所以你只需要传入index

首先阻止*; ...

first[0] //returns the first element
first[1] //returns the second element

在您的示例中,您在首先建立索引时传递的索引值过高,因为您在内部使用了 sizeof。

更正后的代码:

Block& BlockList::operator[](int index) {
    try {
        if (index >= size)
            throw out_of_range("index out of range");
        else 
            return (first[index]);//<--- fix was here
    }
    catch(exception& e) {
        cerr << e.what() << endl;
    }
}

关于c++ - 如何为动态数组实现 operator[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/598036/

相关文章:

C++:字段的类型不完整

arrays - 如何从二维数组中提取聚集数据?

php - 我想在 laravel 的 mongodb 数据中添加数组

asp.net - Web 安装项目无法安装动态数据站点 : "the installer was interrupted"

c# - Webhandler 未在回发时触发

c++ - 带括号的预期的不合格ID错误

c++ - 模拟加速大于最佳

c++ - 删除 vector.end() 失败

javascript - Angular 2为每个数组对象添加键和值

c# - 用于从动态创建的文本框(用 Javascript)捕获数据的 ASP.NET 代码可能是什么样的?