mardi 16 octobre 2018

Output changes when I use Debug-Break-Points in Visual Studio (C++)

I have a very weird problem.

So first of all here are some parts of my code:

Ant Header-File (Constructor and antRoute Methode):

Ant() : route(countcities) {
    //antnumber = _antnumber;
    srand(time(NULL));
    start = rand() % countcities;
    visited.assign(countcities, 0);
    countvisitedCities = 1;
    visited[start] = 1;
    routedistance = 0.0;
    invalidindex = -1;
    probability = vector<double>(countcities);
}



void antRoute() {

    this->route.setCity(0, this->getStartIndex());
    int nextCity = this->getNextCity(this->getStartIndex());
    int tempCity;
    int i = 2;
    this->setProbability(nextCity);
    this->setVisited(nextCity);
    this->route.setCity(1, nextCity);
    updatePheromone(this->getStartIndex(), nextCity, distances[this->getStartIndex()][nextCity]);

    while (this->getVisitedCount() < countcities) {
        tempCity = nextCity;
        nextCity = this->getNextCity(nextCity);
        this->setProbability(nextCity);
        this->setVisited(nextCity);
        this->route.setCity(i, nextCity);
        updatePheromone(tempCity, nextCity, distances[tempCity][nextCity]);
        i++;
    }

    this->route.printRoute();
    cout << endl;


}

Main - Class:

#include "Data.h"
#include "Ant.h"

using namespace std;

int main() {

    init();

    vector<Ant> antarmy;
    antarmy.resize(NUMBERANTS);
    int currentAntNumber = 1;


    for (auto ant = antarmy.begin(); ant != antarmy.end(); ++ant) {
        ant->setNumber(currentAntNumber);
        currentAntNumber++;
        ant->antRoute();
    }



    system("pause");
    return 0;
}

So what this does it creates a vector of objects (Ants) and each ant has a random generated Number (the startindex). Then it uses some other methods to create a route. (ACO-Algorithm)

Thats just for unterstanding. Now something magically happens:

When I debug my code without breaking points all the ants in my vector have the same start index which means the random number it generates in the constructor of each ant is the same.

So my output for the route/city-index-order is always the same.

When I put debug break points into my antRoute-Method and my Main-Function it starts to generate the numbers randomly - the starting index changes and the program runs as it should.

I cant explain why this happens - thanks for your help.




Aucun commentaire:

Enregistrer un commentaire