/*
     Description: 不用经常释放array的内存空间，减少频繁的内存开辟和释放操作

     Copyright : All right reserved by ICT

     Author : Zhang Zhonghai
     Date : 2025/12/29
*/
#pragma once

#include <cstdlib>
#include <vector>

using std::vector;

// 不能用于bool类型, 因为在c++中vector<bool>是特化过的
template <class T>
struct StableArray {
    vector<T> arr;
    size_t idx = 0;
    void clear() { idx = 0; }
    size_t size() { return idx; }
    bool empty() { return idx == 0; }
    void reserve(size_t _size) {
        if (arr.size() < _size)
            arr.reserve(_size);
    }
    void resize(size_t _size) {
        if (arr.size() < _size) {
            arr.resize(_size);
        }
        idx = _size;
    }

    void resize_fill(size_t _size, const T &val) {
        if (arr.size() < _size) {
            arr.resize(_size);
        }
        for (size_t i = 0; i < _size; ++i) {
            arr[i] = val;
        }
        idx = _size;
    }
    void push_back(const T& val) {
        if (idx < arr.size()) {
            arr[idx++] = val;
        } else {
            arr.push_back(val);
            idx++;
        }
    }
    inline T& operator[](size_t pos) { return arr[pos]; }
    //inline const T& operator[](size_t pos) { return arr[pos]; }
    inline const T& operator[](size_t pos) const { return arr[pos]; }
    struct iterator {
        typename std::vector<T>::iterator it;
        iterator(typename std::vector<T>::iterator _it) : it(_it) {}
        iterator& operator++() {
            ++it;
            return *this;
        }
        iterator& operator--() {
            --it;
            return *this;
        }
        T& operator*() const { return *it; }
        bool operator!=(const iterator& other) const { return it != other.it; }
        bool operator==(const iterator& other) const { return it == other.it; }
    };

    iterator begin() { return arr.begin(); }
    iterator end() { return arr.begin() + idx; }
};