So I have this code that is supposed to read from a file. The file depicts a city (sort of) with each item in the file representing a city block. And depending on what character is shown, it is supposed to put it into a class called map and in an object in the class called block set some of it's attributes to distinguish it. Here is what I have for the class Map:
class Map
{
struct coord
{
int x;
int y;
};
public:
struct Block
{
char what;//what is on this block?
coord Coordinate;//coordinates of the block
void SetBlock (char, int, int);
};
};
void Map::Block::SetBlock(char w, int MSCX, int MSCY)
{
what = w;
Coordinate.x = MSCX;
Coordinate.y = MSCY;
}
Now my problem is how do I implement this? I want to have an array of blocks because I don't want to implement each block one at a time (obv). So how would I use a for loop and depending on what character is read set the attribute of each character?
If it helps, the letters in the block represent firestations, the dot represents a block with no obstacles and a star represents a block with obstacles
If you happen to have a better way of solving this, show me please. Thank you!
Are you sure you're not supposed to use the std::map to store your instances of Block inside? The way you have designed the Map class means that you will have a seperate instance of Map each containing a single Block?
#include <map>
usingnamespace std;
struct coord
{
coord(int _x, int _y)
: x(_x), y(_y)
{
}
int x, y;
};
struct Block
{
public:
Block(char _what, coord _coordinate)
: what(_what), coordinate(_coordinate)
{
}
char what;
coord coordinate;
};
typedef map<int, Block*> MAP_TYPE; // you probably want somthing other than int for key, but will do for now
int main()
{
MAP_TYPE mymap;
// to do read file
// get number of elements from file
int element_count(100); // currently some random number which needs to be read from file
// read data from file
for (int n = 0; n < element_count; ++n)
{
char c('a'); // get from file item
coord crd(0,0); // get from file item
int key('k'); // get from file item
Block* block = new Block(c, crd);
mymap.insert(MAP_TYPE::value_type(key, block));
}
//
// do our stuff
//
// delete memory allocated on heap:
for (MAP_TYPE::iterator itr = mymap.begin(); itr != mymap.end(); ++itr)
{
if (itr->second)
{
delete itr->second;
itr->second = NULL;
}
}
return 0;
}