Вектор в одном классе, используемый другим классом, не может хранить элементы - PullRequest
0 голосов
/ 06 мая 2020

У меня есть класс Graph, который заполняет свой вектор Population типа Person (другой класс) информацией из файла. Класс person имеет вектор Conns, в котором хранятся все люди, с которыми человек контактировал. Класс Graph также заполняет вектор Conns в каждом человеке в векторе Population. Код не дает мне никаких ошибок , но когда я печатаю то, что находится в векторе Conns людей в векторе населения , я ничего не получаю .

Это вектор в классе Person и как он к нему добавляется

//Person.h
private:
   std::vector<Person> conns;
public:
   void addConn(Person person);
   void printConns();

//Person.cpp
void Person::addConn(Person person){
    conns.push_back(person);
}

void Person::printConns(){
    if (conns.empty()){
        cout << "There are no connections for " << name << endl;
    }else{
        for (int i = 0; i < conns.size(); i++){
            cout << getName() << "-------" << conns[i].getName() << endl;
        }
    }
}

Вот как класс Graph и как он заполняет вектор Conns в каждом человеке

//Graph.h
private:
   std::vector<Person> population;
   void populate(std::string fileName);
   void addConnections(std::string fileName);
public:
   Graph(std::string pop_file, std::string conn_file);
   Person findPerson(std::string name);

//Graph.cpp
Graph::Graph(string pop_file, string conn_file){
   populate(pop_file); //Add people to the population vector
   addConnections(conn_file); //Add the connections to the respective people
}

void Graph::addConnections(string fileName){
//The file is read and a while loop is used to retrieve info[0] and //info[1] from the file

   Person contacter = findPerson(info[0]); //Get the person object of the "contacter"
   Person contactee = findPerson(info[1]); //Get the person object of the "contactee"

   //Add the connection to the person
   contacter.addConn(contactee)

}

//This method is used to retrieve a person object from a person vector
Person Graph::findPerson(string name){
    if (population.empty()){
        cout << "Empty vector does not contain any one!" << endl;
    }else{
        for (int i =0; i < population.size(); i++){

            //Check if the names are equal and return the person object
            if (population[i].getName().compare(name) == 0){
                return population[i];
            }
        }
    }
}

NB: я получаю правильную информацию, когда распечатываю Contacter и Contactee в addConnections () до и после добавления в вектор Conns

Я распечатываю вектор населения и conns из график в основном файле, но это результат, который я получаю

int main(){
   Graph graph(pop_file, conn_file);
   graph.printPop(); //Prints the info of the people in the population vector
   for (int i = 0; i < graph.getPop().size(); i ++){
       graph.getPop()[i].printConns();  //getPop() returns the population vector
      }
   return 0;
}

Вывод: Имя: Адриенн Возраст: 12 Вероятность распространения: 0,32

Имя: Роберт Возраст: 85 Вероятность распространения: 0,1

Имя: Гэри Возраст: 47 Вероятность распространения: 0,45

Нет подключений для Адриенн

Нет подключений для Роберта

Нет подключений для Гэри

1 Ответ

0 голосов
/ 06 мая 2020
Person contacter = findPerson(info[0]); //Get the person object of the "contacter"
Person contactee = findPerson(info[1]); //Get the person object of the "contactee"

//Add the connection to the person
contacter.addConn(contactee)

contacter - это локальная копия Person в population, а не тот же объект. Таким образом, он добавляет контакт, а затем уничтожается в }, в то время как элемент population не изменился вообще.

Кроме того, в вашем findPerson отсутствует инструкция return, если человек не найден. Не забудьте включить и прочитать предупреждения компилятора, потому что они должны сообщать об этой серьезной проблеме.

Вам нужен указатель или ссылка, чтобы использовать объект из контейнера или иным образом сохраненный в другом месте. Поскольку findPerson на самом деле может не найти Person, вероятно, проще всего использовать указатель, который может иметь значение NULL.

//This method is used to retrieve a person object from a person vector
Person* Graph::findPerson(string name){
    if (population.empty()){
        cout << "Empty vector does not contain any one!" << endl;
    }else{
        for (int i =0; i < population.size(); i++){

            //Check if the names are equal and return the person object
            if (population[i].getName().compare(name) == 0){
                return &population[i]; // *** NOTE THE &
            }
        }
    }
    return nullptr; // *** ADDED
}

void Graph::addConnections(string fileName){
//The file is read and a while loop is used to retrieve info[0] and //info[1] from the file

   Person* contacter = findPerson(info[0]); //Get the person object of the "contacter"
   Person* contactee = findPerson(info[1]); //Get the person object of the "contactee"

   if (contacter && contactee) {
       //Add the connection to the person
       contacter->addConn(*contactee)
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...