I need to implement the task:

Information system at the railway station contains information on the departure of long-distance trains. For each train, the train number, destination station, departure time are indicated. Implement a program that provides the initial data entry into the information system, outputs the entire list, enters the train number and displays all the data about this train, enters the name of the destination station and displays the data about all the trains going to this station. Required with two classes Train and Schedule. But I had a problem using STL libraries. During the search I need to have access to the fields of the train, but I do not know how to implement it

#include <string> #include <list> using namespace std; class Train { public: int number; string arrival_station; float time; //public: Train(); Train(int numb, string arr, float tim); }; class Timetable : public Train { private: Train train; list<Train>* trains; public: Timetable(); void add(Train); int find_number(number); //int find_station(); }; 

Implementations of methods (it is written crookedly and not perfectly :()

 #include "pch.h" #include "Timetable.h" #include <iostream> using namespace std; Train::Train(int numb, string arr, float tim) { if (numb < 24.00) { number = numb; arrival_station = arr; time = tim; } else cout << "\nВремя введено некорректно"; } Train::Train() { } Timetable::Timetable() { } void Timetable::add(Train) { trains.push_back(train); } int Timetable::find_number(number) { list<Train>::const_iterator pos; pos = find(trains.begin(), trains.end(), number) cout << pos->number; } 

    1 answer 1

    You see, you have such a twist that it’s easier to sort out all the errors from scratch ... Therefore, I allow myself to formally limit myself to your question -

    During the search I need to have access to the fields of the train, but I do not know how to implement it

    You need not find() , but find_if() , and you need to use it like this:

     int Timetable::find_number(int num) { list<Train>::const_iterator pos; pos = find_if(trains->begin(),trains->end(),[num](const Train&t){ return t.number == num; }); if (pos == trains->end()) { Не найден } else { Найден } return Что вы там хотели вернуть?... } 

    You do not have a check that something is found, and if it is found, then your pos->number is essentially equal to the function argument (why was it searched? :))

    But all this is minor compared to the general program, which is something strange ...