实验二(第1题)

来源:互联网 发布:2017中国环保产业数据 编辑:程序博客网 时间:2024/05/05 13:44

//seqlist.h头文件

#ifndef seqlist_h

#define seqlist_h
const int maxsize = 100;
class seqlist
{
public:
seqlist()
{
length = 0;
}
seqlist(int a[], int n);
~seqlist(){}
int get(int i);
int locate(int x);
void insert(int i, int x);
int Delete(int i);
void printlist();
private:
int data[maxsize];
int length;
};
#endif



//seqlist.cpp源文件 

#include<iostream>

using namespace std;
#include "seqlist.h" 
seqlist::seqlist(int a[], int n)
{
if (n>maxsize)throw"参数非法";
for (int i= 0; i<n; i++)
{
data[i] = a[i];
length = n;
}


}
int seqlist::locate(int x)
{
for (int i = 0; i<length; i++)
if (data[i] = x)return i + 1;
return 0;
}
int  seqlist::get(int i)
{
if (i<1 && i>length)throw "查找位置非法";
else return data[i - 1];
}
void seqlist::insert(int i, int x)
{
if (length>maxsize)throw"上溢";
if (i<1 || i>length + 1) throw"位置非法";
for (int j = length; j >= i; j--)
data[j] = data[j-1];
data[i-1] = x;
length++;
}
int seqlist::Delete(int i)
{
if (length == 0)throw"下溢";
if (i<1 || i>length)throw"位置非法";
int x = data[i-1];
for (int j = i; j<length; j++)
data[j-1] = data[i];
length--;
return x;
}
void seqlist::printlist()
{
for (int i = 0; i < length; i++)
cout << data[i] << "    ";
   cout << endl;

}



//seqlistmain.cpp源文件

#include<iostream>
using namespace std;
#include"seqlist.h"
void main()
{
int r[5] = { 2, 4, 6, 8, 10};
seqlist L(r, 5);
cout << "执行插入操作前数据为:" << endl;
L.printlist();
try
{
L.insert(2, 3);
}
catch (char *s)
{
cout << s << endl;
}
cout << "执行插入操作后数据为:" << endl;
L.printlist();
cout << "值为4的元素位置为:";
cout << L.locate(4) << endl;
cout << "第三个元素的值为:";
cout << "L.get(3)"<<endl;
cout << "执行删除第一个元素操作,删除前数据为:" << endl;
L.printlist();
try
{
L.Delete(10);
}
catch(char *s)
{
cout << s << endl;
}
cout << "删除后数据为:" << endl;
L.printlist();


0 0
原创粉丝点击