21xrx.com
2024-09-20 00:42:12 Friday
登录
文章检索 我的文章 写文章
顺序表类模板的C++代码和运行结果
2023-06-24 09:08:23 深夜i     --     --
顺序表类 模板 C++代码 运行结果

顺序表是一种常见的数据结构,它可以实现随机存取和顺序存储。在C++中,我们可以使用模板来定义顺序表类,使其具有更好的通用性和灵活性。下面是一个简单的顺序表类模板的C++代码和运行结果。


#include <iostream>

using namespace std;

template<class T>

class SeqList {

private:

  T* data;

  int maxSize;

  int length;

public:

  SeqList(int size) {

    data = new T[size];

    maxSize = size;

    length = 0;

  }

  ~SeqList() {

    delete[] data;

  }

  int getLength() const {

    return length;

  }

  bool isEmpty() const {

    return length == 0;

  }

  bool isFull() const {

    return length == maxSize;

  }

  bool insert(T elem) {

    if (isFull()) {

      return false;

    }

    data[length++] = elem;

    return true;

  }

  bool remove(int index) {

    if (index < 0 || index >= length) {

      return false;

    }

    for (int i = index; i < length - 1; i++) {

      data[i] = data[i + 1];

    }

    length--;

    return true;

  }

  T get(int index) const {

    if (index < 0 || index >= length) {

      return NULL;

    }

    return data[index];

  }

  void display() const {

    for (int i = 0; i < length; i++) {

      cout << data[i] << " ";

    }

    cout << endl;

  }

};

int main() {

  SeqList<int> list(10);

  

  cout << "Is list empty? " << (list.isEmpty() ? "Yes" : "No") << endl;

  cout << "Is list full? " << (list.isFull() ? "Yes" : "No") << endl;

  cout << "Length of list: " << list.getLength() << endl;

  cout << endl;

  list.insert(3);

  list.insert(5);

  list.insert(7);

  list.insert(9);

  cout << "Is list empty? " << (list.isEmpty() ? "Yes" : "No") << endl;

  cout << "Is list full? " << (list.isFull() ? "Yes" : "No") << endl;

  cout << "Length of list: " << list.getLength() << endl;

  list.display();

  cout << endl;

  list.remove(1);

  cout << "Length of list: " << list.getLength() << endl;

  list.display();

  cout << endl;

  int elem = list.get(1);

  cout << "Element at index 1: " << elem << endl;

  return 0;

}

运行结果:


Is list empty? Yes

Is list full? No

Length of list: 0

Is list empty? No

Is list full? No

Length of list: 4

3 5 7 9

Length of list: 3

3 7 9

Element at index 1: 7

从代码和运行结果可以看出,我们定义了一个名为SeqList的模板类,它可以用来创建任意类型的顺序表对象。我们先创建一个最大容量为10的空顺序表,然后逐个插入元素。可以看到,顺序表的长度随着元素的插入而增加。我们还可以通过remove方法来删除指定索引位置的元素,通过get方法来获取指定索引位置的元素。最后,我们输出了结果并释放了SeqList对象占用的内存。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复