目录
线性群体的概念
- 群体是由多个数据元素组成的集合体。群体可以分为两大类:线性群体和非线性群体
- 线性群体中的元素按位置排列有序,可以区分为第一元素、第二元素等。
- 非线性群体不用位置顺序来标识元素。
- 线性群体中的元素次序与其逻辑位置关系是对应的。在线性群体中,又可以按照访问元素的不同方法分为直接访问、顺序访问和索引访问。
- 本章中,我们只介绍直接访问和顺序访问。
数组类模板
- 静态数组是具有固定元素个数的群体,其中的元素可以通过下标直接访问。
- 缺点:大小在编译时就已经确定,运行时无法修改。
- 动态数组由一系列位置连续的、任意数量相同类型的元素组成。
- 优点:其元素个数可以在程序运行时改变。
vector
就是用类模板实现的动态数组。
动态数组类模板程序
#ifndef ARRAY_H
#define ARRAY_H
#include <cassert>
template <class T> // 数组类模板定义
class Array {
private:
T* list; // 用于存放动态分配的数组内存首地址
unsigned size; // 数组大小(元素个数)
public:
Array(unsigned sz = 50); // 默认构造函数
Array(const Array<T> &a); // 拷贝构造函数
~Array();
Array<T> & operator = (const Array<T> &rhs); //拷贝赋值copy assignment,重载"="
T & operator [] (int i); // 重载 "[]"
const T & operator [] (unsigned i) const; // 重载"[]"为常函数
operator T* (); // 重载指针转换符T*
operator const T* () const; // 带有cosnt重载之后,指针指向的内容不可以改变;
unsigned getSize() const;
void resize(int sz); // 修改数组的大小
};
template <class T>
Array<T>::Array(int sz){
// 构造函数
assert(sz >= 0);
size = sz;
list = new T[size]; // 动态分配size个T类型的元素空间
}
template <class T>
Array<T>::~Array(){
// 析构函数
delete [] list;
}
template<class T>
Array<T>::Array(const Array<T> &a){
// 拷贝构造函数
size = a.size; // 从对象a中获取数组的大小
list = new T[size]; // 动态分配n个T类型的元素空间
for(int i = 0; i < size; i++)
list[i] = a.list[i];
}
template <class T>
Array<T>& Array<T>::operator = (const Array<T>& rhs){
if(&rhs != this){
if(size = rhs.size){
delete [] list;
size = rhs.size;
list = new T[size];
}
for(int = 0; i < size; i++)
list[i] = rhs.list[i];
}
return *this; // 返回当前对象的引用
}
template <class T>
T& Array<T>::operator[](int n){
// 重载下标运算符
assert(n >= 0 && n < size);
return list[n];
}
template <class T>
const T& Array<T>::operator[] (int n) const{
assert(n >= 0 && n < size);
return list[n];
}
template <class T>
int Array<T>::getSize() const{
return size;
}
template<class T>
void Array<T>::resize(int sz){
assert(sz >= 0);
if(sz == size)
return;
T* newList = new T[sz];
int n = (sz < size)? sz : size;
for(int i = 0; i < n; i++)
newList[i] = list[i];
list = newList;
size = sz;
}
#endif // ARRAY_H
指针转换运算符的作用简单举例
#include <iostream>
using namespace std;
void read(int *p, int n){
for(int i = 0; i < n; i++)
cin >> p[i];
}
int main(){
int a[10];
read(a,10);
return 0;
}
#include "Array.h"
#include <iostream>
using namespace std;
void read(int* p,int n){
for(int i = 0; i < n; i++)
cin >> p[i];
}
int main(){
Array<int> a(10);
// 重载指针转换符发挥了作用,否则一个对象不会转换成指针
read(a, 10);
return 0;
}
数组类应用举例
- 求范围2~N中的质数,N在程序运行时由键盘输入。
#include <iostream>
#include <iomanip>
#include "Array.h"
using namespace std;
int main() {
Array<int> a(10);
int n,count = 0;
cout << "Enter a value >= 2 as upper limit for prime numbers: ";
cin >> n;
for(int i = 2; i <= n; i++){
bool isPrime = true;
for(int j = 0; j < count; j++){
if(i % a[i] == 0){
isPrime = false;
break;
}
}
if(isPrime){
if