一个动态数组类

简介:
template<class TYPE> class CTArray
{//动态数组类
private:
    UINT    nSize;    // actual size
    UINT    nGrow;    // grow factor

protected:
    UINT    nItems;    // number of elements (as it appears to the user)
    TYPE*    pData;    // pointer to array of data

public:
    // blank constructor
    CTArray() { Init(); }
    
    // copy constructor
    CTArray(CTArray& Src) { Init(); Copy(Src); }
    
    // typed copy constructor
    CTArray(const TYPE* pSrc, UINT nCount = 1)
    {
        Init();
        SetLength(nCount);
        
        for (UINT u = 0; u < nItems; u++) pData[u] = pSrc[u];
    }

    // typed initializing constructor
    CTArray(UINT nCount, TYPE Src)
    {
        Init();
        SetLength(nCount);
        
        for (UINT u = 0; u < nItems; u++) pData[u] = Src;
    }

    // operators
    const TYPE& operator[](UINT nIndex) const { return pData[nIndex]; }
    TYPE&        operator[](UINT nIndex)          { return pData[nIndex]; }
    CTArray&    operator=(CTArray& Src)          { Copy(Src); return *this; }

    // initialise
    void Init() { pData = NULL; nSize = nItems = 0; nGrow = 8; }

    // release data
    virtual void Clear(void) { if (pData != NULL) delete [] pData; Init(); }

    // copy from other
    void Copy(CTArray& Src)
    {
        Clear();
        SetLength(Src.Length());
        
        for (UINT u = 0; u < nItems; u++) pData[u] = Src.pData[u];
    }

    // grow factor get/set
    UINT GrowFactor(void) const { return nGrow; }
    void SetGrowFactor(UINT nNewGrow) { nGrow = nNewGrow; if (nGrow == 0) nGrow = 1; }

    // length (items) get
    UINT Length(void) { return nItems; }
    
    // set length regrow or shrink
    virtual bool SetLength(UINT nLength, bool bForce = false)
    {
        if (nLength == 0)
        {
            Clear();
            return true;
        }
        
        // alloc new storage
        TYPE* pNewData = NULL;
        
        UINT nNewSize = ((nLength / nGrow) + 1) * nGrow;//新数组大小
        
        // grow only if either the amount we need is greater than what we have
        // already or if the amount is <= 1/2, whatever's smaller
        if (nNewSize > nSize || nNewSize <= nSize / 2 || bForce)
        {
            //创建新数组
            if ((pNewData = new TYPE[nNewSize]) == NULL)
                return false;
            
            // now copy the old elements into the new array, up to the old
            // number of items or to the user-set new length,  whichever's
            // smaller
            for (UINT u = 0; u < nItems && u < nLength; u++)
                pNewData[u] = pData[u];
            
            // update all the current info
            if (pData != NULL)
                delete [] pData;
            
            pData = pNewData;
            nSize = nNewSize;
        }
        
        nItems = nLength;
        
        return true;
    }
    
    // set w/bounds check but no grow
    virtual bool Set(UINT nIndex, TYPE Src) const
    {
        if (nIndex >= nItems || pData == NULL)
            return false;

        pData[nIndex] = Src;

        return true;
    }

    // get w/bounds check but no grow
    virtual bool Get(TYPE& Dst, UINT nIndex) const
    {
        if (nIndex >= nItems || pData == NULL)
            return false;

        Dst = pData[nIndex];

        return true;
    }

    // get all elements to a typed pointer; do not forget to delete
    // such pointer after no longer needed
    UINT GetAll(TYPE*& pDst)
    {
        pDst = new TYPE[nItems];

        for (UINT u = 0; u < nItems; u++)
            pDst[u] = pData[u];

        return nItems;
    }

    // get all elements to an unknown size pointer of specified size; the
    // pointer must be initialized by the caller
    UINT GetAll(void* pDst, int nSize)
    {
        for (UINT u = 0; u < nItems; u++)
            memcpy((void*)((BYTE*)pDst + u * nSize), (void*)(&pData[u]), nSize);

        return nItems;
    }

    // remove element at given position
    virtual bool Remove(UINT nIndex)
    {
        if (nItems == 0 || pData == NULL)
            return false;

        // starting with the element we are removing, work up
        // copying each next value down to the current spot
        for (UINT u = nIndex; u < nItems - 1 ; u++)
            pData[u] = pData[u + 1];

        // this will either simply change the nItems value or realloc and
        // free some memory
        SetLength(nItems - 1);

        return true;
    }
    
    // insert element at given position
    virtual void Insert(TYPE Src, UINT nIndex)
    {
        // first, make room
        SetLength(nItems + 1);

        // starting with the last element work back until we get to the one
        // we are inserting at and copy forward
        for (UINT u = nItems - 1; u > nIndex; u--)
            pData[u] = pData[u - 1] ;    

        // finally insert new value
        pData[nIndex] = Src;
    }

    // append element to the end of array
    virtual int Append(TYPE Src)
    {
        // first, make room
        SetLength(nItems + 1);

        // insert new value
        pData[nItems - 1] = Src;

        return nItems;
    }

    // blank append
    virtual int Append()
    {
        // just make room
        SetLength(nItems + 1);
        
        return nItems;
    }

    // finder with mem compare and optional start
    int Find(TYPE Src, UINT nStart = 0)
    {
        for (UINT u = nStart; u < nItems; u++)
        {
            if (memcmp(&pData[u], &Src, sizeof(TYPE)) == 0)
                return (int)u;
        }

        return -1;
    }

    // swap
    void Swap(UINT i, UINT j)
    {
        if (i >= nItems || j >= nItems || i == j)
            return;

        TYPE Tmp = pData[i];
        pData[i] = pData[j];
        pData[j] = Tmp;
    }

    // sort wrapper with callback and method
    void Sort(int (__cdecl* compare)(const void* p1, const void* p2), int nMethod = 0)
    {
        switch (nMethod)
        {
        case 1:
        {
            // sort the array with fixed starting items, by comparing neighbors
            for (UINT i = 0; i < nItems - 1; i++)
            {
                // skip a neighbor that is in order (as determined by a non-zero
                // return from the compare function)
                if (compare((const void*)&pData[i], (const void*)&pData[i + 1]))
                    continue;

                // search for an item matching the last starting item
                UINT j = i + 1;
                
                while (!compare((const void*)&pData[i], (const void*)&pData[j]) && j < nItems - 1)
                    j++;
                
                // swap the matching item to be right below the starting item
                if (j <= nItems - 1)
                    Swap(i + 1, j);
            }
            
            break;
        }
        default:
            qsort(pData, nItems, sizeof(TYPE), compare);
            break;
        }
    }

    // destructor
    ~CTArray() { Clear(); }
};

typedef CTArray<DWORD> DWORDARRAY;



复制代码



本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/07/08/1238455.html,如需转载请自行联系原作者
目录
相关文章
|
7天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
6天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
321 130
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
|
18天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1331 8
|
5天前
|
监控 JavaScript Java
基于大模型技术的反欺诈知识问答系统
随着互联网与金融科技发展,网络欺诈频发,构建高效反欺诈平台成为迫切需求。本文基于Java、Vue.js、Spring Boot与MySQL技术,设计实现集欺诈识别、宣传教育、用户互动于一体的反欺诈系统,提升公众防范意识,助力企业合规与用户权益保护。
|
17天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1412 87
|
6天前
|
人工智能 Java API
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
本文介绍AI大模型的核心概念、分类及开发者学习路径,重点讲解如何选择与接入大模型。项目基于Spring Boot,使用阿里云灵积模型(Qwen-Plus),对比SDK、HTTP、Spring AI和LangChain4j四种接入方式,助力开发者高效构建AI应用。
312 122
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
|
5天前
|
JavaScript Java 大数据
基于JavaWeb的销售管理系统设计系统
本系统基于Java、MySQL、Spring Boot与Vue.js技术,构建高效、可扩展的销售管理平台,实现客户、订单、数据可视化等全流程自动化管理,提升企业运营效率与决策能力。
|
6天前
|
弹性计算 安全 数据安全/隐私保护
2025年阿里云域名备案流程(新手图文详细流程)
本文图文详解阿里云账号注册、服务器租赁、域名购买及备案全流程,涵盖企业实名认证、信息模板创建、域名备案提交与管局审核等关键步骤,助您快速完成网站上线前的准备工作。
253 82
2025年阿里云域名备案流程(新手图文详细流程)