#C++PrimerPlus# Chapter10_Exersice8_v1.0

题意似乎有点难理解,题面提及的链表似乎之前也没介绍过。

从简单做起,定义一个类List:

私有部分:元素数为5的bool类型的数组,false代表列表空,true代表列表满。

       一个计数器,int变量,记录多少个列表项为满。

公有部分:初始化函数,初始空列表。

     添加修改某列表项的函数,以列表项编号为参数。

     访问某编号列表项,返回它的值。(内联)

     检验列表是否为空或满的函数。

     显示整个列表的函数。

程序清单如下:


 

// list.h
#ifndef LIST_H_
#define LIST_H_

// 此处修改列表的数据类型
typedef bool Item;

class List
{
private:
    enum {SIZE = 5};
    Item lists[SIZE];
    int count;
public:
    List();
    void setList(int num);
    const Item& visitList(int num) const {return lists[num-1];}
    bool ifEmpty(void) const;
    bool ifFull(void) const;
    void showLists(void) const;
};

#endif


// list.cpp
#include <iostream>
#include "list.h"

List::List()
{
    for (int i = 0; i < SIZE; i++)
        lists[i] = false;
    count = 0;
}

// 此处修改列表对应数据类型的输入方法
void List::setList(int num)
{
    using std::cout;
    using std::cin;
    cout << "请输入您想要添加进列表项" << num << "的值:";
    if (lists[num-1] != 0)
        count--;
    while (!(cin >> lists[num-1]))
    {
        cin.clear();
        while (cin.get() != '\n')
            continue;
        cout << "输入错误,请重新输入。\n";
    }
    while (cin.get() != '\n')
        continue;
    if (lists[num-1] != 0)
        count++;
}

bool List::ifEmpty(void) const
{
    return count == 0;
}

bool List::ifFull(void) const
{
    return count == 5;
}

// 此处修改列表对应数据类型的输出方法
void List::showLists(void) const
{
    std::cout << "列表状态为:";
    for (int i = 0; i < SIZE; i++)
        std::cout << lists[i];
    std::cout << std::endl;

}


 // uselist.cpp
#include <iostream>
#include "list.h"

int main()
{
    using std::cout;
    using std::cin;
    List newList;
    newList.showLists();
    int listNum;
    cout << "请输入您要修改的列表项编号(1-5),其他任意值退出程序:";
    while (cin >> listNum)
    {
        while (cin.get() != '\n')
            continue;
        newList.setList(listNum);
        newList.showLists();
        if (newList.ifFull())
            cout << "列表已满。\n";
        if (newList.ifEmpty())
            cout << "列表已清空。\n";
        cout << "请输入您要修改的列表项编号(1-5),其他任意值退出程序:";
    }
 
    return 0;
}


结束。

原文链接: https://www.cnblogs.com/zhuangdong/archive/2013/04/27/3044141.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    #C++PrimerPlus# Chapter10_Exersice8_v1.0

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/86200

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午10:26
下一篇 2023年2月9日 下午10:26

相关推荐