第2章 线性表(3)

本文介绍了一个使用C++实现的顺序表数据结构。该顺序表采用std::vector作为底层存储方式,提供了基本的操作如插入、删除、查找等,并且实现了自定义的迭代器。文章通过一个简单的例子展示了如何创建顺序表并进行基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++实现一个顺序表

//Algri.h
#include "stdafx.h"
#include <iostream>
#include <vector>

using std::cout;
using std::vector;

namespace Jeffery
{
template<class T>
class SeqList
{
public:
	int Maxsize;
private:
	vector<T> data;
	int Last;
public:
	T &operator[](size_t index){
		return data[index];
	}

	SeqList(int size){
		data=vector<T>(size);
		Maxsize=size;
		Last=-1;
	}

    void Append(T item){
		if(IsFull())
			cout<<"List is full";
		else
			data[++Last]=item;
	}

    void Clear(){
		Last=-1;
	}

    T Delete(int i){
		T tmp;
		if(IsEmpty())
			cout<<"List is empty";
		else if(i<0||i>Last)
			cout<<"Position is error!";
		else if(i==Last)
			tmp=data[Last--];
		else{
			tmp=data[i];
			for(int j=i+1;j<=Last;++j){
				data[j-1]=data[j];
			}
			--Last;
		}
		return tmp;
	}

    T GetItem(int i){
		if(IsEmpty()||i<0||i>Last){
			cout<<"List is empty or position is error!";
			return T();
		}
		else
			return data[i];
	}

    int GetLength(){
		return Last+1;
	}

    void Insert(T item, int i){
		if(IsFull())
			cout<<"List is full";
		else if(i<0||i>=Last+2)
			cout<<"Position is error!";
		else if(i==Last+1)
			data[++Last]=item;
		else{
			for(int j=Last++;j>=i;--j){
				data[j+1]=data[j];
			}
			data[i]=item;
		}
	}
    bool IsEmpty(){
		if(Last==-1)
			return true;
		else
			return false;
	}
    bool IsFull(){
		if(Last==Maxsize-1)
			return true;
		else
			return false;
	}

    int Locate(T value){
		if(IsEmpty()){
			cout<<"List is Empty!";
			return -1;
		}
		for(int i=0;i<=Last;++i){
			if(value==data[i])
				return i;
		}
		return -1;
	}
};
}
#include "stdafx.h"
#include "Algri.h"
#include <iostream>

using namespace std;
using namespace Jeffery;

int _tmain(int argc, _TCHAR* argv[])
{
	SeqList<int> li= SeqList<int>(10);
	for(int i=0;i<8;i++)
	{
		li.Append(i);
	}

	for(int i=0;i<li.GetLength();i++)
	{
		cout<<li[i]<<", ";
	}
	cout<<endl;

	li.Insert(100,5);
	for(int i=0;i<li.GetLength();i++)
	{
		cout<<li[i]<<", ";
	}
	cout<<endl;

	li.Insert(1000,9);
	for(int i=0;i<li.GetLength();i++)
	{
		cout<<li[i]<<", ";
	}
	cout<<endl;


	li.Delete(2);
	for(int i=0;i<li.GetLength();i++)
	{
		cout<<li[i]<<", ";
	}
	cout<<endl;

	cout<<li.GetItem(7)<<endl;
	cout<<li.Locate(4)<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值