c++ - 将对象插入 C++ 顺序列表

标签 c++ list object sequential

为了学校编程作业,我构建了一个应用程序,将对象列表存储在顺序列表对象中。顺序列表类有一个方法可以将一个新对象插入到列表中,它首先检查列表是否已经达到了允许的最大条目数,如果达到了则返回错误。出于某种原因,我无法将新对象插入到列表中(我不断收到“超出最大列表大小”错误),即使其中没​​有任何要启动的条目。

我用断点运行它以查看大小数据成员是否以某种方式增加,但这里的情况似乎并非如此。

请忽略糟糕的代码质量,仍然只是学习......随时提出任何建议:)

主要程序如下:

#include<iostream>
#include<string>
#include "aseqlist.h"

using namespace std;


void PrintByGender (const SeqList& L, char gender)
    {
        int size = L.ListSize();

        int count = 0;

        while (count < size)
        {

        if (gender == L.GetData(count).getGender())
            {
                L.GetData(count).PrintEmployee();
            }
            count++;
        }

}

int InList (const SeqList& L, char *lname, Employee& Emp)
{
    int found = 0;

    Emp.setLast(lname);

    if (L.Find(Emp) == 1)
    {
        found = 1;
        Emp.PrintEmployee();
    }

    return found;

}

int main()
{
    SeqList obj1;

    bool close = false;
    string choice = "";

    do
    {

        cout << "Please choose what you would like to do: " << "\n";
        cout << "N = New record, D = Delete record, P = Print by gender, S = Search and E = Exit" << "\n";
        cin >> choice;
        cin.ignore();

        if (choice == "n" || choice == "N")
        {

        string first, last;
        int age;
        char gen;
        double empNum;

        cout << "First name: ";
        cin >> first;

        cout << "Last name: ";
        cin >> last;

        cout << "Age: ";
        cin >> age;

        cout << "Gender ('M' Or 'F'): ";
        cin >> gen;

        cout << "Employee Number: ";
        cin >> empNum;

        Employee newEmp;

        newEmp.ReadEmployee(first, last, age, gen, empNum);

        obj1.Insert(newEmp);

        }


        if (choice == "e" || choice == "E")
        {

            close = true;

        }

        if (choice == "p" || choice == "P")
        {
        char genderSearch;
        cout << "Male = M, Female = F";
        cin >> genderSearch;
        cin.ignore();

        PrintByGender(obj1, genderSearch);
        }

        if (choice == "d" || choice == "D")
        {
            string last;
            cout << "Which employee? (Enter Last Name): ";
            cin >> last;
            cin.ignore();

            Employee emp;

            emp.setLast(last);

            obj1.Delete(emp);

            cout << "Deleted";

        }

        if (choice == "s" || choice == "S")
        {

        char lnameSearch;
        cout << "Last Name?: ";
        cin >> lnameSearch;
        cin.ignore();

        Employee emp;

        char *ptrSearch;

        ptrSearch = &lnameSearch;

        InList(obj1, ptrSearch, emp);

        if (emp.getFirst() != "")
        {
            emp.PrintEmployee();

        }

        }

    }
    while (close != true);

};

这是类声明的头文件:

#include <iostream> 

using namespace std;
const int MaxListSize = 6; 
// You will need to change the typedef in the following line
// from the data type int to Employee

class Employee
{

public:
    Employee();
    Employee(string firstName, string lastName, int age, char gender, double employeeNumber);
    void ReadEmployee(string firstName, string lastName, int age, char gender, double employeeNumber);
    char getGender();
    string getFirst();
    void Employee::setLast(string lname);
    string getLast();
    void PrintEmployee();

private:
        string LastName;
        string FirstName;
        int Age;
        char Gender;
        double EmployeeNumber;
};

typedef Employee DataType;
class SeqList 
{ 
   private: 
      // list storage array and number of current list elements 
      DataType listitem[MaxListSize]; 
      int size;

   public: 
      // constructor 
      SeqList(void); 

      // list access methods 
      int ListSize(void) const; 
      int ListEmpty(void) const; 
      int Find (DataType& item) const; 
      DataType GetData(int pos) const; 

      // list modification methods 
      void Insert(const DataType& item); 
      void Delete(const DataType& item); 
      DataType DeleteFront(void); 
      void ClearList(void); 
}; 

// Class Definition: 

// constructor. set size to 0 
SeqList::SeqList (void): size(6) 
{} 

// return number of elements in list 
int SeqList::ListSize(void) const 
{ 
   return size; 
} 

// tests for an empty list 
int SeqList::ListEmpty(void) const 
{ 
   return size == 0; 
} 

// clears list by setting size to 0 
void SeqList::ClearList(void) 
{ 
   size = 0; 
} 

// Take item as key and search the list. return True if item 
// is in the list and False otherwise. if found, 
// assign the list element to the reference parameter item 


bool  operator==(Employee A, Employee B)
{
    bool isequal = false;

    if (A.getLast() == B.getLast())
        isequal = true;

    return isequal;
}


int SeqList::Find(DataType& item) const 
{ 
   int i = 0; 

   if (ListEmpty()) 
      return 0;            // return False when list empty 
   while (i < size && !(item == listitem[i]))
      i++; 
   if (i < size) 
   { 
      item = listitem[i];  // assign list element to item 
      return 1;            // return True 
   } 
   else 
      return 0;            // return False 
} 

// insert item at the rear of the list. terminate the program 
// if the list size would exceed MaxListSize. 
void SeqList::Insert(const DataType& item) 
{ 
   // will an insertion exceed maximum list size allowed? 
   if (size+1 > MaxListSize) 
   { 
      cout << "Maximum list size exceeded" << endl; 
      exit(1); 
   } 

   // index of rear is current value of size. insert at rear 
   listitem[size] = item; 
   size++;                 // increment list size 
} 

// search for item in the list and delete it if found 
void SeqList::Delete(const DataType& item) 
{ 
   int i = 0; 

   // search for item 
   while (i < size && !(item == listitem[i])) 
      i++; 

   if (i < size)           // successful if i < size 
   { 
      // shift the tail of the list to the left one position 
      while (i < size-1) 
      { 
         listitem[i] = listitem[i+1]; 
         i++; 
      } 
      size--;              // decrement size 
   } 
} 

// delete element at front of list and return its value. 
// terminate the program with an error message if the list is empty. 
DataType SeqList::DeleteFront(void) 
{ 
   DataType frontItem; 

   // list is empty if size == 0 
   if (size == 0) 
   { 
      cout << "Attempt to delete the front of an empty list!" << endl; 
      exit(1); 
   } 

   frontItem = listitem[0];  // get value from position 0. 
   Delete(frontItem);        // delete the first item and shift terms 
   return frontItem;         // return the original value 
} 


// return value at position pos in list. if pos is not valid 
// list position, teminate program with an error message. 
DataType SeqList::GetData(int pos) const 
{ 
   // terminate program if pos out of range 
   if (pos < 0 || pos >= size) 
   { 
      cout << "pos is out of range!" << endl; 
      exit(1); 
   } 
   return listitem[pos]; 
}

Employee::Employee()
{

    FirstName = "";
    LastName = "";
    Age = 0;
    /*Gender = "";*/
    EmployeeNumber = 0;

};

Employee::Employee(string firstName, string lastName, int age, char gender, double employeeNumber)
{
        FirstName = firstName;
        LastName = lastName;
        Age = age;
        Gender = gender;
        EmployeeNumber = employeeNumber;
};

void Employee::PrintEmployee()
{
                cout << "First Name: " << FirstName << "\n";
                cout << "Last Name: " << LastName << "\n";
                cout << "Age: " << Age << "\n";
                cout << "Gender: " << Gender << "\n";
                cout << "Employee Number :" << EmployeeNumber << "\n" << "\n";

};

void Employee::ReadEmployee(string firstName, string lastName, int age, char gender, double employeeNumber)
{
        FirstName = firstName;
        LastName = lastName;
        Age = age;
        Gender = gender;
        EmployeeNumber = employeeNumber;
};

char Employee::getGender()
{

    return Gender;
}
string Employee::getFirst()
{
return FirstName;
}
string Employee::getLast()
{
    return LastName;
}
void Employee::setLast(string lname)
{
    LastName = lname;
}

最佳答案

构造函数中的问题:

SeqList::SeqList (void): size(6) 

大小被初始化为 6。

其他建议。不要将 using namespace std; 放在头文件中。更好的是,不要将 using namespace std; 放在任何地方。

Why is "using namespace std" considered bad practice?

关于c++ - 将对象插入 C++ 顺序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15237847/

相关文章:

C++ 整数转二进制

c++ - std::shared_ptr 为 null 但不为空

html - 如何根据 Dart 中的表及其行填充列表?

python - 将列表项添加到另一个列表中的项的末尾

object - Golang - 通过接口(interface)通过 2 步解码/重建对象

c++ - 遍历容器——何时使用引用,何时不使用

python - 不使用 if 但使用 else 的列表推导式

javascript - 将项目添加到数组或替换它(如果它具有相同的 ID)

javascript - Lodash 更新数组之间的值

c++ - 运行在同一台机器上编译的程序时 GLIBCXX 版本错误