#include <iostream>
#include <cstring>
using namespace std;
#define MAXSIZE 10000
struct Book{
string no;
string name;
float price;
Book(){};
Book(string, string, float);
friend bool operator == (Book &book1,Book &book2);//友元函数,重载单目运算符“==”
};
bool operator == (Book &book1,Book &book2){
// book1.no.compare(book2.no)&&book1.name.compare(book2.name)&&(book1.price==book2.price)
if(book1.no.compare(book2.no)){
if(book1.name.compare(book2.name)){
if(book1.price == book2.price){
return true;
}
}
}
else return false;
}
Book::Book(string n, string na, float pr){
no = n;
name = na;
price = pr;
}
struct SqList{
Book *elem;
int length;
};
bool InitList(SqList &L){
L.elem = new Book[MAXSIZE];
if(!L.elem)
return false;
L.length=0;
return true;
}
bool ListInsert(SqList &L,int i, Book e){
if((i<1)||(i>L.length+1))return false;
if(L.length==MAXSIZE)return false;
for(int j=L.length-1;j>=i-1;j--){
L.elem[j+1]=L.elem[j];
}
L.elem[i-1]=e;
++L.length;
return true;
}
bool GetElem(SqList L,int i, Book &e){
if(i<1||i>L.length)return false;
e = L.elem[i-1];
return true;
}
int LocaleElem(SqList L,Book e){
for(int i=0;i<L.length;i++){
if(L.elem[i]==e) return i+1;//使用重载之后的运算符判断两个结构体实例是否相等
}
return 0;
}
bool ListDelete(SqList &L, int i){
if((i<1)||(i>L.length+1))return false;
for(int j=i;j<=L.length-1;j++){
L.elem[j-1] = L.elem[j];
}
--L.length;
return true;
}
void showList(SqList sq){
for(int i=0;i<sq.length;i++){
cout<<sq.elem[i].no<<"\t"<<sq.elem[i].name<<"\t"<<sq.elem[i].price<<endl;
}
}
int main(){
SqList sq;
InitList(sq);
Book book("001","数据结构",35.00);
Book book1("002","C++程序设计",35.00);
cout << "begin" << endl;
ListInsert(sq,1,book);
ListInsert(sq,2,book1);
// cout<<"length:"<<sq.length<<endl;
// 获取元素
/*
Book book2;
GetElem(sq,1,book2);
cout << book2.name << endl;
*/
// 查找位置
/*
cout<<"index:"<<LocaleElem(sq,book1) << endl;
*/
// Book book2("001","数据结构",35.00);
// cout << (book==book2)<<endl;
// 删除线性表数据
cout<<"删除之前"<<endl;
showList(sq);
cout<<ListDelete(sq,1)<<endl;
cout<<"删除之后"<<endl;
showList(sq);
return 0;
}
C++数据结构——线性表的顺序表示和实现
最新推荐文章于 2024-09-11 19:57:20 发布