|
-
October 6th, 2005, 01:19 PM
#1
Need help with struct & vector
Lots of info on structs ... lots of info on vectors ... few websites pay much attention to combining them:
I can't get the declaration correct to use code that creates a struct/vector globally. Why won't this work? ...
In my Globals.h:
struct Blocks {
int x;
int y;
}
extern vector<Blocks*> gBlocks;
In Globals.c:
vector <*Blocks> gBlocks;
I wish to access that in several places, for example:
AddBlock (int x, int y) {
Block *b = new Block;
b->x = x;
b->y = y;
gBlocks.push_back(b);
}
BuildBlocks () {
int x, y;
for (x=1, x<=5, a++) {
y = x*3;
AddBlock (x, y);
}
}
It compiles ... but I get an exit with a corrupt stack (I think). The debugger is showing it choke on the memory allocation for the vector.
However, if I do something like this ...
[No vector setup in Globals like before ... just the struct Block is global.]
AddBlock (int x, int y) {
vector<Block*> gBlocks
Block *b = new Block;
b->x = x;
b->y = y;
gBlocks.push_back(b);
}
BuildBlocks () {
int x, y;
for (x=1, x<=5, a++) {
y = x*3;
AddBlock (x, y);
}
}
What happens is that it will compile and run ... BUT in spite of the multiple calls to AddBlock, I only get a vector with one block in it. Is it the multiple hits on the vector statment in AddBlock that is re-setting the vector? Seems like that is what is happening.
Now, this actually works:
BuildBlocks ();
vector<Block*> gBlocks
int x, y;
for (x=1, x<=5, a++) {
y = x*3;
Block *b = new Block;
b->x = x;
b->y = y;
gBlocks.push_back(b);
}
}
But this is not really what I was going for here. I want to declare the vector/struct globally. In other places in the code, I want to:
(1) Access the vector/struct by using an iterator in a block loop to isolate a single block like 'Block b* = gBlocks[it]'
(2) Make assignments and read a block with 'b->'
(3) Add to the vector with 'Block b* = new Block' ... 'gBlocks.push_back(b)'
(4) Delete individual blocks with gBlocks.erase(it). Delete the whole thing with gBlocks.clear().
Am I setting up the vector globally wrong in the first example? Thanks for any help on this, as I've played around with dozens of changes, but nothing works.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|