c++顺序表储存

#include <iostream>  

#include <string>  

#define MAXSIZE 100

using namespace std;  

struct Book {  

    string id;  

    string name; // 书名  

    double price; // 定价  

};  

typedef struct {  

    Book *elem; //地址  

    int length; //长度  

} SqList;  

//初始化

bool InitList_Sq(SqList &L) {  

    L.elem = new Book[MAXSIZE];  

    if (!L.elem) return false;  

    L.length = 0;  

    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 LocateElem_Sq(SqList L, double e) {  

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

        if (L.elem[i].price == e) return i + 1;  

    }  

    return -1;  

}  

//插入  

bool ListInsert_Sq(SqList &L, int i, Book e) {  

    if (i < 1 || i > L.length + 1 || L.length == MAXSIZE) return false;  

    for (int j = L.length; j >= i; j--) {  

        L.elem[j] = L.elem[j - 1];  

    }  

    L.elem[i - 1] = e;  

    L.length++;  

    return true;  

}  

//删除  

bool ListDelete_Sq(SqList &L, int i) {  

    if (i < 1 || i > L.length) return false;  

    for (int j = i; j < L.length; j++) {  

        L.elem[j - 1] = L.elem[j];  

    }  

    L.length--;  

    return true;  

}  

//输出

void PrintList(SqList L) {  

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

        cout << L.elem[i].id << " " << L.elem[i].name << " " << L.elem[i].price << endl;  

    }  

}

int main() {  

   SqList L;  

    if (!InitList_Sq(L)) {  

        cout << "初始化失败" << endl;  

        return 1;  

    }

  Book b[4];

for(int i=0;i<4;i++)

{

    cin>>b[i].id>>b[i].name>>b[i].price;

 ListInsert_Sq(L, i+1, b[i]);  

  }  

    PrintList(L);  

    // 读取第4个元素  

    Book e;  

    if (GetElem(L, 4, e)) {  

        cout << "第4个元素: " << e.id << " " << e.name << " " << e.price << endl;  

    }  

    // 查找价格是38的图书信息  

    int pos = LocateElem_Sq(L, 38.0);  

    if (pos != -1) {  

        cout << "找到价格为38的图书,位置: " << pos << endl;  

    }  

    // 在第4个元素前插入新元素  

    Book newBook = {"976", "C#面向对象程序设计", 9.0};  

    if (ListInsert_Sq(L, 3, newBook)) {  

        PrintList(L);  

    }  

    // 删除第7个元素  

    if (ListDelete_Sq(L, 7)) {  

        PrintList(L);  

    }  

  delete[] L.elem;

    return 0;  

}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值