文档详情

c++9-new 面向对象.ppt

发布:2017-07-05约1.52万字共76页下载文档
文本预览下载声明
//以下实现各成员函数。 template class T //缺省构造函数的实现 StoreT::Store(): haveValue(false) { } template class T //提取数据函数的实现 T StoreT::getElem() { //如试图提取未初始化的数据,则终止程序 if (!haveValue) { cout No item present! endl; exit(1); //使程序完全退出,返回到操作系统。 } return item; // 返回item中存放的数据 } ArrayT operator = (const ArrayT rhs); T operator [] (int i); //重载[]” const T operator [] (int i) const; operator T * (); //重载到T*类型的转换 operator const T * () const; int getSize() const; //取数组的大小 void resize(int sz); //修改数组的大小 }; for (int i = 2; i = n; i++) { bool isPrime = true; for (int j = 0; j count; j++) if (i % a[j] == 0) { isPrime = false; break; } if (isPrime) { if (count == a.getSize()) a.resize(count * 2); a[count++] = i; } } for (int i = 0; i count; i++) cout setw(8) a[i]; cout endl; return 0; } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * template class T void insertionSort(T a[], int n) { int i, j; T temp; for (int i = 1; i n; i++) { int j = i; T temp = a[i]; while (j 0 temp a[j - 1]) { a[j] = a[j - 1]; j--; } a[j] = temp; } } * * 选择排序的基本思想 每次从待排序序列中选择一个关键字最小的元素,(当需要按关键字升序排列时),顺序排在已排序序列的最后,直至全部排完。 [5 4 10 20 12 3] 初始状态: 3 [4 10 20 12 5] 3 4 [10 20 12 5] 第 i 次选择后,将选出的那个记录与第 i 个记录做交换。 3 4 5 [20 12 10] ... ... * 直接选择排序 在选择类排序方法中,从待排序序列中选择元素的方法不同,又分为不同的选择排序方法,其中最简单的是通过顺序比较找出待排序序列中的最小元素,称为直接选择排序。 例9-12 直接选择排序函数模板(9-12.h) template class T void mySwap(T x, T y) { T temp = x; x = y; y = temp; } template class T void selectionSort(T a[], int n) { for (int i = 0; i n - 1; i++) { int leastIndex = i; for (int j = i + 1; j n; j++) if (a[j] a[leastIndex]) leastIndex = j; mySwap(a[i], a[leastIndex ]); } } * * 交换排序的基本思想 两两比较待排序序列中的元素,并交换不满足顺序要求的各对元素,直到全部满足顺序要求为止。 * 最简单的交换排序方法 ——起泡排序 对具有n个元素的序列按升序进
显示全部
相似文档