Как вернуть объект класса в пустое состояние, чтобы его можно было использовать повторно? - PullRequest
0 голосов
/ 17 мая 2019

Я пишу сценарий начального уровня для моделирования распространения заболевания.Я пытаюсь написать так, чтобы я мог запустить несколько испытаний и вывести результат каждый раз.Скрипт использует класс Person и класс Population, который состоит из вектора лиц.Каждое испытание возвращает один и тот же результат (при индивидуальном тестировании они возвращают разные результаты из одного и того же ввода).Я думаю, что мне нужно стирать мой объект популяции в каждом испытании, но я не совсем уверен, как.

Я думаю, что мне нужен деструктор, но я не уверен в синтаксисе.Онлайновые ресурсы были слишком продвинуты для моего уровня квалификации или давали мне сообщения об ошибках, когда я пытаюсь скопировать их синтаксис

class Person {
  private:  // Person constructor
    int status; bool infected;
  public:
    Person(){
      status = 0; infected = false;
    };

    string status_string(){  // Outputs status of each person with a symbol as a string
      };

     void update_per(){ // Updates status of each person if they are sic
     };

     void infect(int n){ // Infects person if they are susceptible (not recovered or vaccinated)
     };  
     void vaccinate(){ // Changes status of person to being vaccinated
     };
     bool is_stable(){ // Determines if person has recovered from infection
     };
     int get_status() { // Returns status of person
      };

};

class Population {    //Create population class
  private:      //declare private variable npeople
    int npeople;
    vector<Person> population;   //create a vector of Persons named population with size npeople
  public:
    Population(int n){
      srand(time(NULL));
      npeople = n;
      population = vector<Person>(n);
    };
    ~Population()  //DESTRUCTOR
      {
        delete[] population;
      };
    void random_infection(int days){ //method to randomly infect one person
    };

    int count_infected() {    //method to count the number of people infected
    };

    void update_pop(int ncontacts, float contagion, int days) { // Updates the status of each person in population, also simulates spread of disease through contact
    };
    void print_status(){ // Output status of each person in population
    };

    void vacc_pop(float prob){ // Vaccinates a set number of people in the population
    };
};

int main() {
  ofstream popsizeresults;
  int size; // Asks user for size of population
  int numtrials; // Asks user for number of trials
  for (int jjjj=1; jjjj<=numtrials; jjjj++){
    int maxsick = 0;
    int day = 0;
    Population population(size); // Create population
    population.vacc_pop(0.5); // Vaccinate population
    population.random_infection(5); // Infect one random person in population

int step = 1;
    for ( ; ; step++){
      // Output status of each person in population
      cout<<"In step "<<step<< " #sick: "<<population.count_infected()<<" : ";
      population.print_status();
      cout<<endl;
      // If no people are sick, then the disease has run its course
      if(population.count_infected() == 0)
        break;
      // Update the status of each person and simulate spread of disease
      population.update_pop(size*0.25,0.9,5);
    if (population.count_infected() > maxsick){
      maxsick = population.count_infected();
      day = step;
    }    
    }
  popsizeresults.open("disease10.txt", ios::app);
  popsizeresults << jjjj << "," << step << "," << maxsick << "," << day << "\n";
  popsizeresults.close();
  //population.~Population(); //call destructor
  return 0;
  }
}

До того, как я добавил деструктор (он не работает), выходные данные на болезнь10.txt дают разные результаты для каждого испытания, но одинаковые результаты для каждого.Когда он тестируется по одному испытанию за раз (для одних и тех же входных данных), он дает разные результаты (что является целью).Я не уверен, что деструктор на самом деле ответ здесь, я очень плохо знаком с C ++.В любом случае, я не уверен, как повторить разные результаты для каждого испытания.

1 Ответ

0 голосов
/ 17 мая 2019

Теперь я вижу, что вы ищете, вот очень урезанная демонстрация сброса населения.

См. Пронумерованные заметки в комментариях для улучшения стиля и т. Д.

#include <vector>
#include <iostream>

// a very basic Person for exposition
class Person 
{
  public:

    Person() {    };
};

// Population cut down to the bare minimum
class Population 
{
  private:
    // note 1: no need to store npeople. a vector has a size(). Why store the same thing twice
    // note 2: never use `using namespace std;` at global scope. Spell out std:: explicitly 

    std::vector<Person> population;

  public:

    // note 3: number of people can never be negative, so why give ourselves the choice? make it unsiged
    Population(unsigned n)
    // note 4: use list initialisation in constructors
    : population(n)
    {
    };

    // note 5: no need for destructors. google "rule of none", "rule of 5", "rule of 3". Prefer rule of none


    // answer: 
    // a specific function to reset the population
    void reset(unsigned n)
    {
        // destroy old people
        population.clear();

        // make new people
        population.resize(n);
    }

    // note 6: allows us to print a representation of a population for exposition
    friend std::ostream& operator<<(std::ostream& os, Population const& pop)
    {
        for (Person const& p : pop.population)
        {
            os << '.';
        }
        os << "(" << pop.population.size() << " people)";
        return os;
    }
};

int main() 
{
    Population population = Population(10);
    std::cout << population << '\n';

    // note 6: reset the population
    population.reset(5);
    std::cout << population << '\n';
}

Ожидаемый результат:

..........(10 people)
.....(5 people)

Демонстрация в реальном времени: https://coliru.stacked -crooked.com / а / 02868f61f6a3da4d

...