[英]Vector iterator not looping through entire vector
編輯:通過索引迭代並將向量傳遞給函數作為參考都解決了該問題。
我正在創建類似細胞自動機的程序。 有兩類-螞蟻和Doodlebug。 螞蟻用字符“ O”表示,而嘟嘟蟲用字符“ X”表示。 2D字符數組上的空白為“。”
我有一個動態矢量來保存指向對象的指針,因為對象的數量隨着時間的流逝而增加和減少。
我目前正在測試Ant類。 經過三個移動步驟,螞蟻繁殖。 這兩個函數正常工作,所以我正在測試最后一個Ant函數-即將死。
我正在測試一個殺死螞蟻的初始函數(只需將其從字母轉換為數組中的“。”即可),但它似乎並沒有遍歷整個螞蟻向量。 如果我沒有螞蟻“繁殖”,它會按預期工作。
例如,我從6只螞蟻開始。 我讓他們走動,然后全部殺死。 有用。
我從6只螞蟻開始,讓它們移動3次,繁殖,然后嘗試殺死它們。 只有一些對象“死亡”(實際上變成“。”)
我假設問題是繁殖功能-關於我如何添加一個干擾迭代的新對象?
以下是相關的代碼位:
class Ant : public Organism {
Ant(char array[][20]) {
this->x = rand() % 20;
this->y = rand() % 20;
array[x][y] = 'O';
this->count = 0;
}
Ant(char array[][20], int itsX, int itsY) {
this->x = itsX;
this->y = itsY;
array[x][y] = 'O';
this->count = 0;
}
// If adjacent cell = '.', push back a new Ant object
void breed(char array[][20], std::vector<Ant*> colony) {
if (this->count == 2) {
if(!occupied_down(array)) {
Ant* temp = new Ant(array, x+1, y);
colony.push_back(temp);
} else if(!occupied_up(array)) {
Ant* temp = new Ant(array, x-1, y);
colony.push_back(temp);
} else if(!occupied_right(array)) {
Ant* temp = new Ant(array, x, y+1);
colony.push_back(temp);
} else if(!occupied_left(array)) {
Ant* temp = new Ant(array, x, y-1);
colony.push_back(temp);
}
this->count = 0;
}
}
void die(char array[][20]) {
array[this->x][this->y] = '.';
}
};
void moveAnts(char step[][20], std::vector<Ant*> colony) {
std::vector<Ant*>::iterator itr;
for(itr = colony.begin(); itr < colony.end(); ++itr) {
Ant* temp = *itr;
temp->move(step);
}
}
void breedAnts(char step[][20], std::vector<Ant*> colony) {
std::vector<Ant*>::iterator itr;
for(itr = colony.begin(); itr < colony.end(); ++itr) {
Ant* temp = *itr;
temp->breed(step, colony);
}
}
void killAnts(char step[][20], std::vector<Ant*> colony) {
std::vector<Ant*>::iterator itr;
for(itr = colony.begin(); itr < colony.end(); ++itr) {
Ant* temp = *itr;
temp->die(step);
}
}
int main() {
srand(time(NULL));
char step[20][20];
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
step[i][j] = '.';
}
}
std::vector<Ant*> colony;
for(int i = 0; i < 6; i++) {
Ant* test = new Ant(step);
colony.push_back(test);
}
for(int i = 0; i < 4; i++) {
print(step);
moveAnts(step, colony);
breedAnts(step, colony);
}
killAnts(step, colony);
print(step);
return 0;
}
更改功能以參考矢量。 您似乎通過價值傳遞了它們。 例如。 更改
void moveAnts(char step[][20], std::vector<Ant*> colony)
至
void moveAnts(char step[][20], std::vector<Ant*>& colony)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.