服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++ 动态数组模版类Vector实例详解

C++ 动态数组模版类Vector实例详解

2022-10-08 15:58诺谦 C/C++

这篇文章主要为大家详细介绍了C++动态数组模版类Vector实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

1.实现机制

内部主要通过m_capacity数组容量成员和m_length数组有效长度成员来维护一个T* data数组空间.

内部默认分配一定数量大小的数组指针,每次append尾部追加的时候,无需再次分配空间,直接赋值标志length长度,假如超过当前空间容量,则再次扩大分配新的内存数组,并将旧数组拷贝至新数组及释放旧数组.

Vector需要实现的public函数如下所示:

  • inline int capacity() 获取容量
  • inline int length() : 获取有效长度
  • void resize(int asize) : 改变数组的有效长度
  • void append(const T &t) : 尾部追加一个元素
  • T& operator[] (int i) : 通过[]获取元素
  • T operator[] (int i) const : 通过[]获取常量元素
  • void clear() :清空数组中的数据
  • inline bool isEmpty(): 数组是否有数据

resize()函数实现细节:

  • 如果resize长度大于当前容量时 : 则扩大分配新的内存数组,并将旧数组拷贝至新数组及释放旧数组.
  • 如果resize长度小于当前length时 : 则需要将多余的成员进行释放,调用析构函数实现.
  • 如果resize长度大于当前length时 : 则需要调用默认构造函数来填充内部数组.

2.代码实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#ifndef VECTOR_H
#define VECTOR_H
#include "throw.h"
// throw.h里面定义了一个ThrowException抛异常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg)  {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
template <typename T>
class Vector
{
    T* m_data;
    int m_length;       // 有效数据的长度
    int m_capacity;     // 分配容量的长度
    // 分配
    T* allocate(int size)
    {
        T* arr = new T[size];
        if(arr == NULL) {
            ThrowException( "No memory to create DynamicArray object ...");
        }
        return arr;
    }
    // 重新分配
    void realloc(int capacity)
    {
        T* newData = allocate(capacity);
        for(int i=0; i<m_length; i++) {
            newData[i] = m_data[i];
        }
        delete[] m_data;
        m_data = newData;
        m_capacity = capacity;
    }
    // 调用析构函数
    void destruct(int from, int end)
    {
        while(from++<end) {
           m_data[from].~T();
        }
    }
    // 调用默认构造函数
    void defaultConstruct(int from, int end)
    {
        while(from++<end) {
           m_data[from] = T();
        }
    }
public:
    Vector(int lenght = 50)  { m_length = 0; m_data = allocate(lenght); m_capacity = lenght; }
    inline int capacity() const { return m_capacity; }     // 获取容量
    inline int size()  { return m_length; }         // 获取有效长度
    inline int length()  { return size(); }
    inline T *data() {  return m_data; }
    inline const T *data() const { return m_data; }
    inline bool isEmpty() const { return m_length == 0; }
    void clear()
    {
        if(!m_length) return;
        destruct(0, m_length);
        m_length = 0;
    }
    void resize(int asize)
    {
        if(asize == m_length) return;
        // 重新分配的大小>当前容量时
        if(asize > m_capacity) {
            realloc(asize);
        }
        if (asize < m_length)    // 分配的大小<当前大小时,则调用析构
            destruct(asize, m_length);
        else        // 分配的大小>当前大小时,则调用默认构造
            defaultConstruct(m_length, asize);
        m_length = asize;
    }
    // 尾部追加一个元素
    void append(const T &t)
    {
        if(m_length == m_capacity) {
            realloc(m_capacity+20);     // 如果容量满了,则默认增加20个容量.方便后面append无需再次分配内存
        }
        m_data[m_length] = t;
        m_length++;
    }
    T& operator[] (int i)
    {
        if((0 <= i) && (i < length()))
        {
            return m_data[i];
        }
        else
        {
            ThrowException("Parameter i is invalid ...");
        }
    }
    T operator[] (int i) const
    {
        return m_data[i];
    }
};
#endif // VECTOR_H

3.测试运行

测试如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Test {
public:
    int number;
    Test(int n = 0) {
        number = n;
    }
};
int main(int argc, char *argv[])
{
   Vector<Test> arr;
   for(int i = 0; i < 10; i++)
       arr.append(Test(i));
   cout<<"********* Arr Len:"<<arr.length()<<" capacity:"<<arr.capacity()<<endl;
   for(int i = 0; i < arr.length(); i++)
       cout<<"arr []:"<<arr[i].number<<endl;
   cout<<"*********"<<endl;
   arr.resize(13);
   cout<<"********* Arr Len:"<<arr.length()<<" capacity:"<<arr.capacity()<<endl;
   for(int i = 0; i < arr.length(); i++)
       cout<<"arr []:"<<arr[i].number<<endl;
   cout<<"*********"<<endl;
   arr.resize(5);
   cout<<"********* Arr Len:"<<arr.length()<<" capacity:"<<arr.capacity()<<endl;
   for(int i = 0; i < arr.length(); i++)
       cout<<"arr []:"<<arr[i].number<<endl;
   cout<<"*********"<<endl;
    return 0;
}

运行如下所示:

C++ 动态数组模版类Vector实例详解

可以看到我们resize(13)后,由于 resize长度大于当前arr的length,所以则调用默认构造函数来填充内部数组.所以arr[10]至arr[12]的number为0。

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!  

原文链接:https://blog.csdn.net/qq_37997682/article/details/123111695

延伸 · 阅读

精彩推荐
  • C/C++C语言实现推箱子游戏的代码示例

    C语言实现推箱子游戏的代码示例

    这篇文章主要介绍了C语言实现推箱子游戏的代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们...

    ZackSock5822021-08-03
  • C/C++一篇文章教你如何用C语言实现strcpy和strlen

    一篇文章教你如何用C语言实现strcpy和strlen

    这篇文章主要为大家介绍了C语言实现strcpy和strlen的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助...

    黎丶辰6122022-08-11
  • C/C++C 二分查找 递归与非递归的实现代码

    C 二分查找 递归与非递归的实现代码

    C 二分查找 递归与非递归的实现代码,需要的朋友可以参考一下...

    C语言教程网2302020-11-19
  • C/C++c++关键字const的用法详解

    c++关键字const的用法详解

    在类中,如果你不希望某些数据被修改,可以使用const关键字加以限定。const 可以用来修饰成员变量、成员函数以及对象,希望能够给你带来帮助...

    沉迷编程4922022-01-10
  • C/C++C++ 将一个文件读入数组再读出数组的方法

    C++ 将一个文件读入数组再读出数组的方法

    今天小编就为大家分享一篇C++ 将一个文件读入数组再读出数组的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    除妖人8682021-06-30
  • C/C++c语言的注释定界符详解

    c语言的注释定界符详解

    在本文里小编给大家分享的是关于c语言的注释定界符知识点详解,需要的朋友们可以跟着学习下。...

    angryTom4672021-08-16
  • C/C++融会贯通C++智能指针教程

    融会贯通C++智能指针教程

    本文主要介绍了c++的基础知识,通过不带引用计数的只能指针和带引用的智能指针,shared_ptr和weak_ptr,多线程访问共享对象的线程安全问题以及自定义删除...

    只会写bug~4552021-12-24
  • C/C++c++11 chrono全面解析(最高可达纳秒级别的精度)

    c++11 chrono全面解析(最高可达纳秒级别的精度)

    chrono是c++ 11中的时间库,本文就来详细的介绍一下chrono库的具体使用,关键是理解里面时间段(Durations)、时间点(Time points)的概念,感兴趣的可以了解一下...

    帝江VII11592022-03-07