A
A
Alexander Markelov2021-09-30 17:40:32
OOP
Alexander Markelov, 2021-09-30 17:40:32

Removing and adding objects to a dynamic array through a function?

There is an array of class Train and fields destination, departure time, number of passengers and ticket price. In one of the menu items, you are given the right to enter a destination in order to delete one of the objects that satisfies the condition (the Delete function) and in the other of the items you need to add a train by position in the array, which is entered from the keyboard (Add function). Please help, what is the problem, why these functions do not work correctly, the one that should delete only the first field of the first element, the second one inserts the entered train into position 0, and the one that needs to be added by the constructor ...

Actually the code itself:

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

class Train
{
  private:
    string dest; // пункт назначения
    string dep_time; // время отправления
    int pas_number; // количество пассажиров
    int price; // стоимость билета

  public:
    Train(string des, string dep, int numb, int pr )
    {
      dest = des;
      dep_time = dep;
      pas_number = numb;
      price = pr;
    }

    Train()
    {
      dest="---";
      dep_time="---";
      pas_number=0;
      price=0;
    }

    ~Train()
    {
      cout << "Уничтожение объекта класса Train" << endl;
    }


    int GetPas()
    {
      return pas_number;
    }
    void SetPas()
    {
      cout << "Количество пассажиров:";
      cin >> pas_number;
    }
    string GetDest()
    {
      return dest;
    }
    void SetDest()
    {
      cout << "Пункт назначения::";
      cin >> dest;
    }
    void SetPrice()
    {
      cout << "Цена билета(в леях):";
      cin >> price;
    }

    int GetPrice()
    {
      return price;
    }
    string GetTime()
    {
      return dep_time;
    }
    void SetTime()
    {
      cout << "Время отправления";
      cin >> dep_time;
    }

    void GetTrain()
    {
      cout << "\nПункт назначения:" << dest
           << "\nВремя отправления:" << dep_time
           << "\nКоличество пассажиров:" << pas_number
           << "\nСтоимость билета:" << price << "лей" << endl;
    }
    void SetTrain()
    {
      SetDest();
      SetTime();
      SetPas();
      SetPrice();
    }

};

void Input(Train train[], int numb_trains)
{
  for( int i=0; i < numb_trains; i++ )
    train[i].SetTrain();
}
void Output(Train train[], int numb_trains)
{
  for( int i=0; i < numb_trains; i++ )
    train[i].GetTrain();
}

void Sort(Train train[],int numb_trains)
{
    Train *temp = new Train;

    for(int i = 0; i < numb_trains ; i++)
        for (int j = i + 1; j < numb_trains; j++)
            if (train[i].GetPas() < train[j].GetPas() )
            {
                *temp = train[i];
                train[i] = train[j];
                train[j] = *temp;
            }
}
void Delete(Train *train, int numb_trains)
{
  string y;
  Train *newarray = new Train[numb_trains - 1];
  cout << "\nВведите время отправления для удаления поезда:"<< endl; cin >> y;

  for(int i=0,j=0 ; i < numb_trains; i++)
  {
    if( train[i].GetDest() == y )
    {
      j++;
      continue;
    }
    else
      newarray[i - j] = train[i];
  }
  --numb_trains;
  delete[] train;
  train = newarray;

}
void Add(Train*& train, int numb_trains)
{
  int i,k,j;
  do
  {
  cout << "Введите позицию с в которую хотите вставить новый поезд:"; cin >> k;
  }while( k < 0 || k > numb_trains );

  Train* newarray = new Train[numb_trains + 1];
  ++numb_trains;

  for ( i=0, j=0; i < numb_trains ; i++)
  {
    if( i == k )
    {
      newarray[j].SetTrain();
      j++;
      continue;
    }
    newarray[i] = train[i - j];
  }

  delete []train;
  train = newarray;
}
void ComparePrice(Train *train, int numb_trains)
{
  int x;
  cout << "Введите цену билета:"; cin >> x;

  for( int i=0; i < numb_trains; i++)
  {
    if( train[i].GetPrice() > x )
    {
      cout << "\nПоезд " << i+1 << " имеет цену билета выше " << x << " лей" << endl;
      train[i].GetTrain();
    }
  }
}
int main()
{
  setlocale(LC_ALL,"ru");

int choice,numb_trains=6;
string y;
  Train *train = new Train[numb_trains];
  train[0]={"Chisinau","16:00",24,60};
  train[1]={"Cagul","16:50",56,50};
  train[2]={"Tighina","13:00",20,90};
  train[3]={"Tiraspol","17:00",10,100};
  train[4]={"Edinet","18:00",75,70};
  train[5]={"Dubasari","17:40",45,80};
    do{
  do
  {
  cout << "Главное меню:" << endl;
  cout << "1.Ввод информации о каждом поезде;" << endl;
  cout << "2.Вывод информации о каждом поезде;" << endl;
  cout << "3.Cортировка поездов в порядке убывания по количество пассажиров;" << endl;
  cout << "4.Вывод на экран поездов, для которых известно, что стоимость билета выше x" << endl;
  cout << "5.Добавление нового поезда" << endl;
  cout << "6.Удаление поезда, для которого известен пункт назначения равен y" << endl;
  cout << "7.Выход" << endl;
  cout << "Ваш выбор:" << endl;
  cin >> choice;

  } while( choice < 1 || choice > 7  );

  switch(choice)
  {
    case 1: Input(train,numb_trains); break;
    case 2: Output(train,numb_trains); break;
    case 3: Sort(train,numb_trains); break;
    case 4: ComparePrice(train,numb_trains); break;
    case 5: Add(train,numb_trains); break;
    case 6: Delete(train,numb_trains); break;
    case 7: cout << "Спасибо! Удачи!" << endl; break;
    default: cout << "Ошибка!" << endl;
  }
    }while(choice != 7);
return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-30
@lucky_bastard

void Add(Train*& train, int numb_trains)
numb_trains should be a link, otherwise you change it in the function, and outside, no one cares.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question