我有一个很奇怪的问题。
首先,这是我的代码的某些部分:
Ant头文件(构造函数和antRoute方法):
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;
}
主要-类:
#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;
}
那么,它创建了一个对象向量(Ants),每个蚂蚁都有一个随机生成的Number(起始索引)。然后,它使用其他一些方法来创建路由。 (ACO算法)
那只是为了理解。现在发生了一些神奇的事情:
当我调试代码时没有断点时,向量中的所有蚂蚁都具有相同的起始索引,这意味着它在每个蚂蚁的构造函数中生成的随机数是相同的。
所以我对route / city-index-order的输出始终是相同的。
当我在我的antRoute-Method和Main-Function中放置调试断点时,它开始随机生成数字-起始索引发生变化,程序按预期运行。
我无法解释为什么会发生-感谢您的帮助。