我正在尝试编写一个函数generate_labyrinth()
,它创建了一个固定数量的随机连接节点。每个节点都与其他三个节点连接。
以下是我现在所拥有的:
labyrinth.h
:
#ifndef LABYRINTH_H
#define LABYRINTH_H
// node
class Room {
public:
Room ()
: room_number(0), left_door(nullptr),
center_door(nullptr), right_door(nullptr) { }
// data member
int room_number;
// pointers to other nodes
Room* left_door;
Room* center_door;
Room* right_door;
};
//=================================================
class Labyrinth {
public:
Labyrinth (int s) : size(s) { generate_labyrinth (); }
private:
// number of nodes
int size;
// root node
Room* entrance;
// Helper functions
int random_number (int from, int to);
int random_number_without_i (int min, int max, int i);
// Initialiazation function
void generate_labyrinth ();
};
#include "labyrinth.cpp"
#endif
labyrinth.cpp
:
// Class Labyrinth member implementations
int Labyrinth::random_number (int min, int max) {
static bool seed_initialized = false;
if (!seed_initialized) {
seed_initialized = true;
srand((unsigned int) time(NULL));
}
return rand() % (max - min + 1) + min;
}
int Labyrinth::random_number_without_i (int min, int max, int i) {
int res = random_number(min, max);
while (res == i){
res = random_number(min, max);
}
return res;
}
void Labyrinth::generate_labyrinth () {
// create "size" number of nodes
entrance = new Room[size];
// initialize Room (node) data members
for (auto i = 0; i < size; ++i) {
entrance[i].room_number = i;
}
// connect each room with three others
int first_room = 1;
int last_room = size - 1;
for (int i = 1; i < size; ++i) {
// avoid connecting a room with itself
int left_goes_to = random_number_without_i (first_room, last_room, i);
int center_goes_to = random_number_without_i (first_room, last_room, i);
int right_goes_to = random_number_without_i (first_room, last_room, i);
entrance[i].left_door = (&entrance[left_goes_to]);
entrance[i].center_door = (&entrance [center_goes_to]);
entrance[i].right_door = (&entrance [right_goes_to]);;
}
// TEST IF NODES POINT TO EACH OTHER
for (auto i = 0; i < size; ++i) {
if (entrance[i].left_door == nullptr || entrance[i].center_door == nullptr ||
entrance[i].right_door == nullptr) {
std::cout <<"Uninitialized pointer value\n";
}
}
getchar();
}
main
:
#include <iostream>
#include <time.h>
#include "labyrinth.h"
//=================================================
int main()
{
int cave_size = 20;
Labyrinth cave(cave_size);
}
似乎在generate_labyrinth ()
中的节点初始化后,三个指针left_room
,center_room
,right_room
仍然未初始化,即我得到的输出是:
Uninitialized pointer value
为什么节点中的指针没有初始化?
是否有其他方法可以生成随机连接的节点集?
注意:我没有使用insert()
函数,因为在构造数据结构期间固定并确定了节点数。
答案 0 :(得分:2)
您为first_room
与last_room
生成了1
到size-1
的房间。
// connect each room with three others
int first_room = 1;
int last_room = size - 1;
for (int i = 1; i < size; ++i) {
但是当你检查连接时,你从房间0
开始(可能应该是入口本身)。
// TEST IF NODES POINT TO EACH OTHER
for (auto i = 0; i < size; ++i) {