我们利用静态分配的数组来实现的顺序表的局限还是挺大的,主要在于它的容量是预先定好的,用户不能根据自己的需要来改变。如果为了后续用户能够自己调整顺序表的大小,动态地分配数组空间还是很有必要的。基于动态分配的数组的顺序表绝大部分跟基于静态分配的数组的顺序表是一样的,只需在后者程序上改动一小部分即可。

  第一,我们不需定义一个容量常量CAPACITY,而是定义一个私有变量myCapacity。

  第二,类的构造函数需要改进一下。我们需要类在被实例化时自动申请内存,即需添加下边程序:

  1. ElementType * seqList = new ElementType(myCapacity);
    assert(seqList != NULL);

  第三,类的析构函数需要添加下边一句:

  1. delete [] seqList;

  上面三点说的还有所欠缺。Larry Nyhoff在《数据结构与算法分析》第253页中提到设计类时要记住的一条规则:

  如果类在运行时使用new分配内存,则它应该提供:

  • 把动态分配的内存还给堆的析构函数。
  • 编译器用来创建不同副本的复制构造函数。
  • 程序员用来创建不同副本的赋值运算符。

  基于动态分配的数组的顺序表设计的类如下:

  1. // seqlist.h
  2. #ifndef SEQLIST
  3. #define SEQLIST
  4.  
  5. #include <iostream>
  6. #include <cassert>
  7. #include <algorithm>
  8.  
  9. using namespace std;
  10.  
  11. typedef int ElementType;
  12.  
  13. class SeqList
  14. {
  15. public:
  16. SeqList(const int maxsize = );
  17. virtual ~SeqList();
  18. SeqList(const SeqList& origList);                // 拷贝构造函数,记得防止浅拷贝
  19. const SeqList& operator=(const SeqList& rightHandSide); // 重载赋值运算符,记得防止浅拷贝
  20. bool empty() const;
  21. void clear();
  22. bool insert(const int pos, const ElementType val);
  23. bool erase(const int pos);
  24. void display() const;
  25. bool setSeqList(const ElementType *tmpList, const int len);
  26. int getLenOfList() const;
  27. ElementType getItem(const int pos);
  28. ElementType * getSeqList();                   // 保留,不推荐使用,因为在使用过程中无法进行越界检查
  29.  
  30. private:
  31. int myCapacity;                          // 自定义顺序表容量
  32. int lenOfList;                           // 顺序表长度
  33. ElementType * seqList;
  34.  
  35. };
  36.  
  37. #endif

  实现程序为:

  1. // seqlist.cpp
  2. #include <iostream>
  3. #include <cassert>
  4. #include "seqlist.h"
  5.  
  6. using namespace std;
  7.  
  8. SeqList::SeqList(const int maxsize)
  9. {
  10. // initialization
  11. lenOfList = ;
  12. myCapacity = maxsize;
  13. seqList = new ElementType[myCapacity];
  14. // assert(seqList != NULL);
  15. if (seqList == NULL)
  16. {
  17. cerr << "Inadequate memory to allocate stack." << endl;
  18. throw bad_alloc();
  19. }
  20. }
  21.  
  22. SeqList::~SeqList()
  23. {
  24. delete[] seqList;
  25. }
  26.  
  27. SeqList::SeqList(const SeqList& origList)
  28. {
  29. myCapacity = origList.myCapacity;
  30. lenOfList = origList.lenOfList;
  31. seqList = new ElementType[myCapacity];
  32. // assert(seqList != NULL);
  33. if (seqList == NULL)
  34. {
  35. cerr << "Inadequate memory to allocate stack." << endl;
  36. throw bad_alloc();
  37. }
  38. else
  39. {
  40. for (int i = ; i < lenOfList; i++)
  41. {
  42. seqList[i] = origList.seqList[i];
  43. }
  44. }
  45. }
  46.  
  47. const SeqList& SeqList::operator=(const SeqList& rightHandSide)
  48. {
  49. // 确保不是自我赋值
  50. if (this != &rightHandSide)
  51. {
  52. // 如果需要,分配一个新数组
  53. if (myCapacity != rightHandSide.myCapacity)
  54. {
  55. delete[] seqList;
  56. myCapacity = rightHandSide.myCapacity;
  57. seqList = new ElementType[myCapacity];
  58. // assert(seqList != NULL);
  59. if (seqList == NULL)
  60. {
  61. cerr << "Inadequate memory to allocate stack." << endl;
  62. throw bad_alloc();
  63. }
  64. }
  65.  
  66. lenOfList = rightHandSide.lenOfList;
  67. for (int i = ; i < lenOfList; i++)
  68. {
  69. seqList[i] = rightHandSide.seqList[i];
  70. }
  71. }
  72. return *this;
  73. }
  74.  
  75. bool SeqList::empty() const
  76. {
  77. return lenOfList == ;
  78. }
  79.  
  80. void SeqList::clear()
  81. {
  82. lenOfList = ;
  83. fill(seqList, seqList + myCapacity - , );
  84. }
  85.  
  86. bool SeqList::insert(const int pos, const ElementType val)
  87. {
  88. bool success = false;
  89. // assert(lenOfList != CAPACITY); // 这里的assert分成两行写,是为了方便定位错误发生的地方
  90. // assert(0 <= pos <= lenOfList);
  91. if (lenOfList == myCapacity)
  92. {
  93. cerr << "No space for insertion!" << endl;
  94. }
  95. else if (pos < || pos > lenOfList)
  96. {
  97. cerr << "The position " << pos <<
  98. " you want to insert is less than zero or exceeds the length of the list!" << endl;
  99. throw out_of_range("throw out_of_range"); // 抛出一个越界异常
  100. }
  101. else
  102. {
  103. int tmpCount = lenOfList - pos;
  104. for (int i = ; i < tmpCount; i++)
  105. {
  106. seqList[lenOfList - i] = seqList[lenOfList - i - ];
  107. }
  108. seqList[pos] = val;
  109. lenOfList++;
  110. success = true;
  111. }
  112. return success;
  113. }
  114.  
  115. bool SeqList::erase(const int pos)
  116. {
  117. bool success = false;
  118. // assert(lenOfList != 0);
  119. // assert(0 <= pos <= lenOfList);
  120. if (lenOfList == )
  121. {
  122. cerr << "There is no elements in the list!" << endl;
  123. }
  124. else if (pos < || pos > lenOfList)
  125. {
  126. cerr << "The position " << pos <<
  127. " you want to erase is less than zero or exceeds the length of the list!" << endl;
  128. throw out_of_range("throw out_of_range"); // 抛出一个越界异常
  129. }
  130. else
  131. {
  132. int tmp = lenOfList - pos;
  133. for (int i = ; i < tmp - ; i++)
  134. {
  135. seqList[pos + i] = seqList[pos + i + ];
  136. }
  137. seqList[lenOfList - ] = ;
  138. lenOfList--;
  139. success = true;
  140. }
  141. return success;
  142. }
  143.  
  144. void SeqList::display() const
  145. {
  146. cout << "***Start Displaying***" << endl;
  147. if (lenOfList == )
  148. {
  149. cerr << "There is no element in the the list!" << endl;
  150. }
  151. else
  152. {
  153. for (int i = ; i < lenOfList; i++)
  154. {
  155. cout << i << " : " << seqList[i] << endl;
  156. }
  157. cout << "***End Displaying***" << endl;
  158. }
  159. }
  160.  
  161. bool SeqList::setSeqList(const ElementType *tmpList, const int len)
  162. {
  163. // assert(len <= CAPACITY);
  164. bool success = false;
  165. if (len <= myCapacity)
  166. {
  167. for (int i = ; i < len; i++)
  168. {
  169. seqList[i] = *(tmpList++);
  170. }
  171. lenOfList = len;
  172. success = true;
  173. }
  174. else
  175. {
  176. cerr << "The length of the array you set exceeds the CAPACITY." << endl;
  177. throw out_of_range("throw out_of_range"); // 抛出一个越界异常
  178. }
  179. return success;
  180. }
  181.  
  182. int SeqList::getLenOfList() const
  183. {
  184. return lenOfList;
  185. }
  186.  
  187. ElementType SeqList::getItem(const int pos)
  188. {
  189. // assert(0 <= pos <= lenOfList);
  190. if (pos < || pos > lenOfList)
  191. {
  192. cerr << "The item at " << pos << " you want to get does not exist!" << endl;
  193. throw out_of_range("throw out_of_range"); // 抛出一个越界异常
  194. }
  195. else
  196. {
  197. return seqList[pos];
  198. }
  199. }
  200.  
  201. ElementType * SeqList::getSeqList()
  202. {
  203. return seqList;
  204. }

seqlist.cpp

  Boost单元测试程序为:

  1. // BoostUnitTest.cpp
  2. #define BOOST_TEST_MODULE ArrayList_Test_Module
  3.  
  4. #include "stdafx.h"
  5. #include "D:\VSProject\Algorithm\List\SeqList\SeqList_BsedOnDynamicArray\SeqList\seqlist.h"
  6.  
  7. struct ArrayList_Fixture
  8. {
  9. ArrayList_Fixture()
  10. {
  11. BOOST_TEST_MESSAGE("Setup fixture");
  12. testArrayList = new SeqList();
  13. }
  14. ~ArrayList_Fixture()
  15. {
  16. BOOST_TEST_MESSAGE("Teardown fixture");
  17. delete testArrayList;
  18. }
  19.  
  20. SeqList * testArrayList;
  21. };
  22.  
  23. // BOOST_AUTO_TEST_SUITE(ArrayList_Test_Suite)
  24. BOOST_FIXTURE_TEST_SUITE(ArrayList_Test_Suite, ArrayList_Fixture)
  25.  
  26. BOOST_AUTO_TEST_CASE(ArrayList_Abnormal_Test)
  27. {
  28. // Set values to the array list
  29. int testArray[] = { , , , , }; // 5 个元素
  30. int testLenOfList = sizeof(testArray) / sizeof(int);
  31. testArrayList->setSeqList(testArray, testLenOfList);
  32. // BOOST_REQUIRE_THROW(testArrayList->setArrayList(testArray, testLenOfList), out_of_range);
  33.  
  34. // Method getItem-----------------------------------------------
  35. // If the position of the item you want to get is less than zero
  36. BOOST_REQUIRE_THROW(testArrayList->getItem(-), out_of_range);
  37. // If the position of the item you want to get is larger than the length of the list
  38. BOOST_REQUIRE_THROW(testArrayList->getItem(), out_of_range);
  39.  
  40. // Method insert-------------------------------------------------
  41. // If the inserting position is less than zero
  42. BOOST_REQUIRE_THROW(testArrayList->insert(-, ), out_of_range);
  43. BOOST_REQUIRE(testArrayList->getLenOfList() == testLenOfList);
  44.  
  45. // If the inserting position is larger than the length of the list
  46. BOOST_REQUIRE_THROW(testArrayList->insert(, ), out_of_range);
  47. BOOST_REQUIRE(testArrayList->getLenOfList() == testLenOfList);
  48.  
  49. // Method erase-------------------------------------------------
  50. // If the erasing position is less than zero
  51. BOOST_REQUIRE_THROW(testArrayList->erase(-), out_of_range);
  52. BOOST_REQUIRE(testArrayList->getLenOfList() == testLenOfList);
  53.  
  54. // If the erasing position is larger than the length of the list
  55. BOOST_REQUIRE_THROW(testArrayList->erase(), out_of_range);
  56. BOOST_REQUIRE(testArrayList->getLenOfList() == testLenOfList);
  57.  
  58. }
  59.  
  60. BOOST_AUTO_TEST_CASE(ArrayList_Normal_Test)
  61. {
  62. bool expected;
  63. bool actual;
  64. // Method empty-------------------------------------------------
  65. expected = true;
  66. actual = testArrayList->empty();
  67. BOOST_REQUIRE(expected == actual);
  68.  
  69. // Set values to the array list
  70. int testArray[] = { , , , , }; // 5 个元素
  71. int testLenOfList = sizeof(testArray) / sizeof(int);
  72. testArrayList->setSeqList(testArray, testLenOfList);
  73. // BOOST_REQUIRE_THROW(testArrayList->setArrayList(testArray, testLenOfList), out_of_range);
  74.  
  75. // Method getItem-----------------------------------------------
  76. BOOST_REQUIRE(testArrayList->getItem() == testArray[]);
  77.  
  78. // Method empty-------------------------------------------------
  79. expected = false;
  80. actual = testArrayList->empty();
  81. BOOST_REQUIRE(expected == actual);
  82.  
  83. // Method insert-------------------------------------------------
  84. expected = true;
  85. actual = testArrayList->insert(, );
  86. BOOST_REQUIRE(expected == actual);
  87. BOOST_REQUIRE(testArrayList->getLenOfList() == testLenOfList + );
  88. BOOST_REQUIRE(testArrayList->getItem() == );
  89.  
  90. // Method erase-------------------------------------------------
  91. expected = true;
  92. actual = testArrayList->erase();
  93. BOOST_REQUIRE(expected, actual);
  94. BOOST_REQUIRE(testArrayList->getLenOfList() == testLenOfList);
  95. BOOST_REQUIRE(testArrayList->getItem() == testArray[]);
  96.  
  97. }
  98.  
  99. BOOST_AUTO_TEST_CASE(ArrayList_CopyConstructor_Test)
  100. {
  101. bool expected;
  102. bool actual;
  103. // Set values to the array list
  104. int testArray[] = { , , , , }; // 5 个元素
  105. int testLenOfList = sizeof(testArray) / sizeof(int);
  106. testArrayList->setSeqList(testArray, testLenOfList);
  107. // BOOST_REQUIRE_THROW(testArrayList->setArrayList(testArray, testLenOfList), out_of_range);
  108.  
  109. // Copy constructor
  110. //SeqList * copySeqList(testArrayList); // 极容易写成这样子。错误。
  111. // 需要给copySeqList分配内存
  112. SeqList * copySeqList = new SeqList(*testArrayList);
  113.  
  114. // Method getItem-----------------------------------------------
  115. BOOST_REQUIRE(copySeqList->getItem() == testArray[]);
  116.  
  117. // Method empty-------------------------------------------------
  118. expected = false;
  119. actual = copySeqList->empty();
  120. BOOST_REQUIRE(expected == actual);
  121.  
  122. // Method insert-------------------------------------------------
  123. expected = true;
  124. actual = copySeqList->insert(, );
  125. BOOST_REQUIRE(expected == actual);
  126. BOOST_REQUIRE(copySeqList->getLenOfList() == testLenOfList + );
  127. BOOST_REQUIRE(copySeqList->getItem() == );
  128.  
  129. // Method erase-------------------------------------------------
  130. expected = true;
  131. actual = copySeqList->erase();
  132. BOOST_REQUIRE(expected, actual);
  133. BOOST_REQUIRE(copySeqList->getLenOfList() == testLenOfList);
  134. BOOST_REQUIRE(copySeqList->getItem() == testArray[]);
  135. }
  136.  
  137. BOOST_AUTO_TEST_CASE(ArrayList_EqualOperator_Test)
  138. {
  139. bool expected;
  140. bool actual;
  141. // Set values to the array list
  142. int testArray[] = { , , , , }; // 5 个元素
  143. int testLenOfList = sizeof(testArray) / sizeof(int);
  144. testArrayList->setSeqList(testArray, testLenOfList);
  145. // BOOST_REQUIRE_THROW(testArrayList->setArrayList(testArray, testLenOfList), out_of_range);
  146.  
  147. // Copy constructor
  148. SeqList * copySeqList = new SeqList();
  149. // copySeqList = testArrayList; // 极易犯的一个低级错误
  150. *copySeqList = *testArrayList;
  151.  
  152. // Method getItem-----------------------------------------------
  153. BOOST_REQUIRE(copySeqList->getItem() == testArray[]);
  154.  
  155. // Method empty-------------------------------------------------
  156. expected = false;
  157. actual = copySeqList->empty();
  158. BOOST_REQUIRE(expected == actual);
  159.  
  160. // Method insert-------------------------------------------------
  161. expected = true;
  162. actual = copySeqList->insert(, );
  163. BOOST_REQUIRE(expected == actual);
  164. BOOST_REQUIRE(copySeqList->getLenOfList() == testLenOfList + );
  165. BOOST_REQUIRE(copySeqList->getItem() == );
  166.  
  167. // Method erase-------------------------------------------------
  168. expected = true;
  169. actual = copySeqList->erase();
  170. BOOST_REQUIRE(expected, actual);
  171. BOOST_REQUIRE(copySeqList->getLenOfList() == testLenOfList);
  172. BOOST_REQUIRE(copySeqList->getItem() == testArray[]);
  173. }
  174.  
  175. BOOST_AUTO_TEST_SUITE_END();

BoostUnitTest.cpp

  本篇博文的代码均托管到Taocode : http://code.taobao.org/p/datastructureandalgorithm/src/.

"《算法导论》之‘线性表’":基于动态分配的数组的顺序表的更多相关文章

  1. "《算法导论》之‘线性表’":基于静态分配的数组的顺序表

    首先,我们来搞明白几个概念吧(参考自网站数据结构及百度百科). 线性表 线性表是最基本.最简单.也是最常用的一种数据结构.线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外, ...

  2. C++利用动态数组实现顺序表(不限数据类型)

    通过类模板实现顺序表时,若进行比较和遍历操作,模板元素可以通过STL中的equal_to仿函数实现,或者通过回调函数实现.若进行复制操作,可以采用STL的算法函数,也可以通过操作地址实现.关于回调函数 ...

  3. C语言利用动态数组实现顺序表(不限数据类型)

    实现任意数据类型的顺序表的初始化,插入,删除(按值删除:按位置删除),销毁功能.. 顺序表结构体 实现顺序表结构体的三个要素:(1)数组首地址:(2)数组的大小:(3)当前数组元素的个数. //顺序表 ...

  4. 使用JAVA数组实现顺序表

    1,引入了JAVA泛型类,因此定义了一个Object[] 类型的数组,从而可以保存各种不同类型的对象. 2,默认构造方法创建了一个默认大小为16的Object数组:带参数的构造方法创建一个指定长度的O ...

  5. 《算法导论》习题解答 Chapter 22.1-8(变换邻接表的数据结构)

    一般散列表都与B+树进行比较,包括在信息检索中也是. 确定某条边是否存在需要O(1). 不足: (1)散列冲突. (2)哈希函数需要不断变化以适应需求. 另外:B+树.(见第18章) 与散列表相比的不 ...

  6. $Django 多对多-自定义第三张表 基于双下划线的跨表查询(补充)

    自定义第三张表的好处:可以定义多个字段, 缺点:查询不方便(有方法解决) 1.第三张表设置外键,联合唯一(查询不方便) class Books(models.Model): name=models.C ...

  7. YTU 2989: 顺序表基本运算(线性表)

    2989: 顺序表基本运算(线性表) 时间限制: 1 Sec  内存限制: 128 MB 提交: 1  解决: 1 题目描述 编写一个程序,实现顺序表的各种基本运算(假设顺序表的元素类型为char), ...

  8. C# 数据结构 线性表(顺序表 链表 IList 数组)

    线性表 线性表是最简单.最基本.最常用的数据结构.数据元素 1 对 1的关系,这种关系是位置关系. 特点 (1)第一个元素和最后一个元素前后是没有数据元素,线性表中剩下的元素是近邻的,前后都有元素. ...

  9. 基于C++的顺序表的实现

    顺序表,是数据结构中按顺序方式存储的线性表,又称向量.具有方便检索的特点.以下,是笔者学习是基于C++实现的顺序表代码,贴上来当网页笔记用. #include <iostream> usi ...

随机推荐

  1. Not saving crash log because we have reached the limit for logs to store on disk.解决办法

    一.问题简述: Xcode, window>Devices>DEVICES选中自已的设备,打开控制台:提示日志存量已达限制,这个是系统抛出的log."Not saving cra ...

  2. Memcached - In Action

    Memcached 标签 : Java与NoSQL With Java 比较知名的Java Memcached客户端有三款:Java-Memcached-Client.XMemcached以及Spym ...

  3. 【伯乐在线】最值得阅读学习的 10 个 C 语言开源项目代码

    原文出处: 平凡之路的博客   欢迎分享原创到伯乐头条 伯乐在线注:『阅读优秀代码是提高开发人员修为的一种捷径』http://t.cn/S4RGEz .之前@伯乐头条 曾发过一条微博:『C 语言进阶有 ...

  4. zookeeper分布式部署方案

    版本:http://apache.fayea.com/zookeeper/zookeeper-3.4.8/环境:debian 7/8说明:最低配置3台步骤:1.下载zookeeper-3.4.8并解压 ...

  5. win8如何共享文件夹

    最近小编接手了市委组织部考核项目,各种文档.ER图.原型图,组员之间需要拷来拷去,很不方便,通过飞信,QQ传输吧,文件太大,网络太慢,所以还是不行,于是小编就想起来要共享,以前也映射过别人的共享,觉得 ...

  6. Swift函数柯里化(Currying)简谈

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 下面简单说说Swift语言中的函数柯里化.简单的说就是把接收多 ...

  7. 6.4、Android Studio的GPU Monitor

    Android Monitor包含GPU Monitor,它将可视化的显示渲染窗体的时间.GPU Monitor可以帮助你: 1. 迅速查看UI窗体生成 2. 辨别是否渲染管道超出使用线程时间 在GP ...

  8. (一一九)通过CALayer实现阴影、圆角、边框和3D变换

    在每个View上都有一个CALayer作为父图层,View的内容作为子层显示,通过layer的contents属性决定了要显示的内容,通过修改过layer的一些属性可以实现一些华丽的效果. [阴影和圆 ...

  9. 编译GDAL支持MySQL

    GDAL支持MySQL需要MySQL的库才可以,编译很简单,修改nmake.opt文件中对应的MySQL的库的路径和lib即可. nmake.opt文件中397行左右,如下: # MySQL Libr ...

  10. 06_NoSQL数据库之Redis数据库:Redis的高级应用之登录授权和主从复制

     Redis高级实用特征 安全性(登录授权和登录后使用auth授权) 设置客户端连接后进行任何其他指定前需要使用的密码. 警告:因为redis速度相当快,所以在一台比较好的服务器下,一个外部的用户 ...