• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Need some quick C++ help: classes

Status
Not open for further replies.

Ecrofirt

Member
ok I've made a class. Normally to make an object you'd do this:

Code:
ENEMY bug;

and bug was now an object of the ENEMY class.

What I want to do though, is create an array of bugs, like bug[1], bug[2], bug[3], etc.

I need to have 50-100 of these, and later on I'm gonig to have a for loop that goes through them like so:

Code:
for(int i=1; i<=10;i++) {

    if(bug[i].visible=true) {
      
       blah;

    }

}

How do I go about making an array of them?

I'm using .NET 2003, if that helps with anything.

Thanks guys.
 

Ecrofirt

Member
ok, thank you.

And if I needed to be able to use delete on them later, can I create them like this:

bug=new ENEMY[50];
?

from what I've read in the MSDN, you can only use the delete function if you've used new to create something.
 

aaaaa0

Member
Ecrofirt said:
ok, thank you.

And if I needed to be able to use delete on them later, can I create them like this:

bug=new ENEMY[50];
?

from what I've read in the MSDN, you can only use the delete function if you've used new to create something.

just be careful when you delete them later on you need to do:

delete [] bug;

NOT

delete bug;
 
Ecrofirt said:
ok, thank you.

And if I needed to be able to use delete on them later, can I create them like this:

bug=new ENEMY[50];
?

from what I've read in the MSDN, you can only use the delete function if you've used new to create something.

Yeah, only use delete when you've used new. If you wanted to declare the array dynamically you can do it like this:
ENEMY *bug = new ENEMY[50];
 

maharg

idspispopd
If you create them as an array you don't need to delete them. They're on the stack and are automatically destructed.

If you need a variable number of them, or you want to be able to easily copy them, you should use a vector rather than directly calling new and delete.

Code:
#include <vector>

...

std::vector<ENEMY> enemies(nEnemies);

And then to copy it somewhere else you just use = to assign it to the other location.

To loop through a vector, there are a couple of ways:
Code:
// similar to what you are already used to:
for (int i = 0; i < enemies.size(); i++)
{ ... }

// using an iterator:
for (std::vector<ENEMY>::iterator i = enemies.begin(); i != enemies.end(); i++)
{ ... }
The second is more verbose, but also more general.

If you don't know that you need to manually manage the memory, please don't try. It's a common newbie mistake to think you understand memory management before you understand all the different choices of object lifespan and ownership. I'm not trying to be mean by telling you that you probably don't, only honest. Learn the ropes with automatic memory management and then branch out when you understand the problems manual memory management actually solves and the fact that you *should not* be solving every problem with it.
 

Ecrofirt

Member
Another quick question, this time about global variables.

So far, this is the only way I've learned to use global variables:
Code:
int number= 1;

void main(int argc, char *argv[])
{
   
   number++ //will add 1 on to the number without arrors

}

But what I need to do now is basically make a global variable inside a function, like this:

Code:
void main(int argc, char *argv[])
{

   init_enemies();
   
   bug=7; //just something silly so you can see what I mean
              // this is, however where I will get the error, as bug isn't a global variable.

}


void init_enemies()
{
   
   int bug=1;
   int rat=2;  //just to give some idea of what I mean.
   int dog=3;


}

I need them to be global, as I use the same variables across multiple functions (movement, collision detection, blitting to the screen, etc.)

What can I do to accomplish this without a problem?
 

Ecrofirt

Member
I mean, shit, I don't even know if what I'm asking is possible.

It probably isn't.

What I'd like to do is call a function from my main() that will initialize all the things I'll need (in this case, it's my player object and th earray of enemy objects for the level).

Currently I've got them in a init_level() function.

I'd like to have a CollisionCheck() function that I don't have to send the objects to, and I can just check the values on.

This probably isn't really possible.
 

DaMan121

Member
Ecrofirt said:
I mean, shit, I don't even know if what I'm asking is possible.

It probably isn't.

What I'd like to do is call a function from my main() that will initialize all the things I'll need (in this case, it's my player object and th earray of enemy objects for the level).

Currently I've got them in a init_level() function.

I'd like to have a CollisionCheck() function that I don't have to send the objects to, and I can just check the values on.

This probably isn't really possible.

Dont see why its not possible. Although gloabl variables are frowned upon by purists, its usually a quick and dirty (just like sex :p) solution.
Anyway, no exactly sure what you mean when you say this:

"But what I need to do now is basically make a global variable inside a function, like this:"

and this:

"I need them to be global, as I use the same variables across multiple functions (movement, collision detection, blitting to the screen, etc.)"

because when you declare a global variable it IS available in all functions to access (all functions that 'know' about it ofcourse.. if your function is in another source code file, you will need to make use of extern )

so..

int bug = 0;

int main()
{


}

void function1()
{
bug = 1;
}

void function2()
{
bug = 7;
}

etc.

The problem is keeping track of it though, since its global, debuging can be a bitch,
 

Ecrofirt

Member
yea, but look at my second set of code.

I don't have the variable declared outside the main function.

Basically what I want to do is declare a global variable inside a function.

Here's an example. Say I've got a config file for every level in my game. Well, the level 1 config file says there's 12 enemies

I can't do this:
Code:
*bug = new ENEMY[12];

void main() {

blah;

}

void collision () {

blah;

}

void draw_GFX() {

blah;

}

because say the level 2 config file says there's 30 enemies. Well then, the code is now incorrect, as it's trying to make a 12 element array.

So what I need is something like this:
Code:
void main () {

init_enemies();

blah;
}

void init_enemies() {

*bug= new ENEMY[whatever];  //value taken from config file

}

where bug would now be global. Again, notice I haven't declared it at the top, i'm making an array in a function, and I want that array to be global.

Is something like this possible? With the programming knowledge I currently have, I don't know how to do something like this.
 

iapetus

Scary Euro Man
DaMan121 said:
Although gloabl variables are frowned upon by purists, its usually a quick and dirty (just like sex :p) solution.

Heh. I was just about to frown upon them.

And for the record, while they may be like sex, it's like bad drunken sex with a crack-addled whore with half her teeth missing and the other half rotten and god alone knows how many STDs. Don't do it.
 

RiZ III

Member
Theres a couple of ways of handling globals. One of my favs is singletons. This is probably not what you want in your case because im assuming your going to have more than one rat and bug and all. Singletons are good for anything of which there is only going to be one instance. Like a window. Google it if your interested.

Another way is to break it all down into classes, and then have a manager class.

Code:
class Rat; 
class Bug;
class Dog;

class Handler
{
private:
      vector<Rat> vRats;
      vector<Bug> vBugs;
      vector<Dog> vDogs;

public:
      void Loop();
       ~Handler();
};

//where the loop handles all the different bugs,rats, dogs. Its called once every frame or //game loop.
void Handle::Loop()
{
    //if there are less than ten rats, create a new one
    if(vRats.size() < 10)  
     {
            Rat newRat;  //this will call the constructor and initialize the rat
            ...   //set any other variables in this new rat object
            vRats.push_back(newRat);
     }

     //vectors have fast random access, so u can access them like arrays
    for(int i = 0; i < vRats.size(); ++i)
    {
           vRats[i].Handle();  //will handle all the rat stuff like ai, drawing, etc.
    }

    /*note here you will need three for loops. One for bug, one for rats, one for dogs. 
 If you have a 100 types of creatures, u'll need a hundred for loops. Baaad. 
This is where inheritance and polymorphism come in handy.  If the rat, dog, and bug were 
all derived from a base class with a virtual function Handle, then u'll only need one for         
loop.  vCreature[i]->Handle().  Notice that im using the -> operator, thats because now 
the vCreatures vector will be something like this:*/
 
vector<Creatures *> vCreatures; //its a vector of pointers to creatures
                                                //well things get a bit complicated here, but your   purposes, the multiple for loops with no pointers is good enuff i think. 
}

//ofcourse you want to clear all the vectors once ur done
Handler::~Handler()
{
     vRats.clear(); //same for the dog and bug
}

edit: tagged with code
edit: now technically, this handler class could actually be implemented as a singleton because there will probably be only one instance of it, but its not necessary to make it a singleton.
 

Ecrofirt

Member
ok RiZ, so what you're saying is to make my normal classes, and then also make a handler class that will handle adding and deleting rats and all that jazz.

now in my main() in my normal game loop, I would call the loop function in the handler?
 

DaMan121

Member
where bug would now be global. Again, notice I haven't declared it at the top, i'm making an array in a function, and I want that array to be global.

Is something like this possible? With the programming knowledge I currently have, I don't know how to do something like this.

Ok, much clearer now. What you want is a dynamic array, not static so:

CBug *bugArray = NULL; //initilize to NULL

int main()
{
whatever();
}

void init_level()
{
//Check if bug pointer points to valid memory
if(bugArray){
delete [] bugArray;
}

//Get number of bugs for new level
int numberOfBugs = GetNumberOfBugsFromFile();

//allocate new memory
bugArray = new CBug[numberOfBugs ];
}

This help?

Edit: Riz's methos is much more neater.. and use of STL's saves on shitload of probs you will encounter when dealing with arrays (unless you write your own dynamic array class, but with so many out there its a waste of time imo).
 

Panajev2001a

GAF's Pleasant Genius
iapetus said:
Heh. I was just about to frown upon them.

And for the record, while they may be like sex, it's like bad drunken sex with a crack-addled whore with half her teeth missing and the other half rotten and god alone knows how many STDs. Don't do it.

Just like PlayStation 2 development ;).


Sometimes globals and extern "C" statements are REALLY a BIG BIG help there where you have to micro-manage everything and are however punished badly for any mistake :(.


From Quake II's source code (this is only from the beginning of their BSP code, there is more ;)).

Code:
//
// current entity info
//
qboolean		insubmodel;
entity_t		*currententity;
vec3_t			modelorg;		// modelorg is the viewpoint reletive to
								// the currently rendering entity
vec3_t			r_entorigin;	// the currently rendering entity in world
								// coordinates

float			entity_rotation[3][3];

int				r_currentbkey;

typedef enum {touchessolid, drawnode, nodrawnode} solidstate_t;

#define MAX_BMODEL_VERTS	500			// 6K
#define MAX_BMODEL_EDGES	1000		// 12K

static mvertex_t	*pbverts;
static bedge_t		*pbedges;
static int			numbverts, numbedges;

static mvertex_t	*pfrontenter, *pfrontexit;

static qboolean		makeclippededge;

Globals are used ;).




Maharg, I heard that every time you use STD or anything from ATL a PlayStation 2 programmer gets a headache.
 

RiZ III

Member
In main you would have something like this.

Code:
#include "handler.h" //assuming u either include the header files for the creatures in the handle.h file or above this include.

void main()
{
       Handler creatureHandler;

       while(1) //main loop
       {
             ...//do whatever
             creatureHandler.Loop();
            ...//do whatever

       }
}
 

DaMan121

Member
Also, not sure what environment your using (win32 / mfc?), but its also handy to create a GameState base class, with a bunch of virtuals handling keyboard / mous input , draw , etc and then inherit from it for things like PLayState, GameOverState, IntroState ... Just something I learnt the hard way when dealing with my pet gaming projects.
 

Ecrofirt

Member
when I get this finished, you guys will be able to play, as long as I don't have problems porting it back to PC code from where it's at now.

And a few of you will be able to play it in the state it's in now without problems.
 

maharg

idspispopd
Panajev2001a said:
Maharg, I heard that every time you use STD or anything from ATL a PlayStation 2 programmer gets a headache.

I have seen the typical C++ game programmer's replacement for the standard library, and it is depressing how horrible they are. Let them have headaches.

Besides, it's irrelevant what some bigshot game coder would use. Actually suggesting someone who is clearly *learning* use the most complex techniques off the bat is just plain lame.

Shame on anyone actually propagating the idea he should be using new and delete for such a simple little program.
 

NohWun

Member
Ecrofirt said:
...
So what I need is something like this:
Code:
void main () {

init_enemies();

blah;
}

void init_enemies() {

*bug= new ENEMY[whatever];  //value taken from config file

}

where bug would now be global. Again, notice I haven't declared it at the top, i'm making an array in a function, and I want that array to be global.

Is something like this possible? With the programming knowledge I currently have, I don't know how to do something like this.

You need to learn the difference between a "variable declaration" and a "variable definition". Here's a random page that explains it: http://www.savinov.spb.ru/think/tic0028.html

You can declare the variable each in level file. You would define it only once, perhaps in the "main" file.
 

alejob

Member
You can't create a global variable inside a function, thats how local functions are created :p. You can, however, use parameters.
 

Panajev2001a

GAF's Pleasant Genius
maharg said:
I have seen the typical C++ game programmer's replacement for the standard library, and it is depressing how horrible they are. Let them have headaches.

You mean you have seen the ASM code ? Hehe.

At least on PlayStation 2 a lot of the big studioshave a poor soul that gets the fun job of re-writing in ASM tons of lines of C/C++ code: thanks GCC :).

My point was not that their alternatives were more elegant and necessarily more powerful and all... it is that they were in CONTROL, which is what console developers want and need. Know what happens, when it happens and the trade-offs made to achieve it.

Besides, it's irrelevant what some bigshot game coder would use. Actually suggesting someone who is clearly *learning* use the most complex techniques off the bat is just plain lame.

I was not, darn maharg... I cannot even crack a joke anymore ;).

Shame on anyone actually propagating the idea he should be using new and delete for such a simple little program.

I know... go to .NET, get him to learn C# (or Java) and he will be making games without doing manual memory management (2D or 3D... managed Direct3D is available).

I was introduced to pointers (and new and delete) towards the end of my VERY first introduction class to C++ in college. I am more iffy about using STD and Templates in general than using pointers and new and delete (no, I am not Michael Abrash either :p), but that is just me, I am not saying templates are not useful and besides I have never managed a project in which the sheer size would make templates a god-sent gift (besides this little PS2Linux project, but I have not seen a clea clear use there yet, but then it is not even close to be finished so... ;)).



I would seriously suggest Java for him if he does not want to use pointers and do manual memory management with new and delete.
 

Ecrofirt

Member
Pana, with the system I'm working for I have no choice but to use C++.

I've got Java classes in college, so I'm really taking a lot of the stuff I've learned there and applying it to C++ (I had a very redimentary C++ course in collin C++. I say this, because our teacher was so bad that she couldn't get her own simple programs to compile. The concept of a class was nearly impossible to grasp with her, but easy as pie once I had some Java in college).

I've taken it upon myself to learn some C++ from www.gametutorials.com, and that's where I saw new and delete (we've been using new with java when creating arrays, which is what I wanted to do here).

Anyway, it's unfortunate I can't really talk more about what I'm doing, but I don't want to get myself in trouble with anyone.
 

maharg

idspispopd
Panajev2001a said:
My point was not that their alternatives were more elegant and necessarily more powerful and all... it is that they were in CONTROL, which is what console developers want and need. Know what happens, when it happens and the trade-offs made to achieve it.

You know what, I was going to rant about this, because I personally feel that it's completely wrong in so many ways, but I'm not going to because I've already used up my quota of advanced C++ technique evangelism for the year. I'm trying to cut down ;P

Ecrofirt said:
I've taken it upon myself to learn some C++ from www.gametutorials.com, and that's where I saw new and delete (we've been using new with java when creating arrays, which is what I wanted to do here).

Being new, the *right way* to create dynamic arrays in C++ for you is vector<>, NOT new and delete. C++ is not java. C++ in fact only bears a superficial resemblence to Java. The appropriate techniques for each language are not the same and you should not attempt to keep the superficial resemblence at the expense of using the language correctly.

Even in games, the need to manually manage memory to the extreme that is often presented as correct is decreasing all the time as developers catch up to compiler improvements. A lot of studios are still stuck with older compilers because that's what the platform supports, but the studios that are moving up are by and large using more advanced techniques.

Drop this tutorial and go get a good book on C++. Accelerated C++ is excelent and relatively short and cheap ($20 on amazon, I believe). The C++ Programming Language, written by the creator of the language, is also very good though much less introductory.

Do yourself a favour and do that, because the job market for C++ programmers who think they understand memory management but don't is going to shrink rapidly as C++ programs have to compete ever more with languages that take care of it for you. You can *easily* have nearly the level of ease of memory management in C++ as you're used to in Java if you just pick up a good book on the subject and use the right libraries.

(this was not an advanced C++ rant, and as such does not count under the above quota. Things like vector<> and other parts of the standard library are no longer advanced topics and should not be treated as such)
 

Panajev2001a

GAF's Pleasant Genius
maharg said:
You know what, I was going to rant about this, because I personally feel that it's completely wrong in so many ways, but I'm not going to because I've already used up my quota of advanced C++ technique evangelism for the year. I'm trying to cut down ;P



Being new, the *right way* to create dynamic arrays in C++ for you is vector<>, NOT new and delete. C++ is not java. C++ in fact only bears a superficial resemblence to Java. The appropriate techniques for each language are not the same and you should not attempt to keep the superficial resemblence at the expense of using the language correctly.

Even in games, the need to manually manage memory to the extreme that is often presented as correct is decreasing all the time as developers catch up to compiler improvements. A lot of studios are still stuck with older compilers because that's what the platform supports, but the studios that are moving up are by and large using more advanced techniques.

Well, I am not denying that with ICC 8.x, MSVC 7.x and a modern Intel processor or AMD processor many programmers are moving to higher level programming and less ASM and manual memory management.

In the case of PlayStation 2 the market for programmers who KNOW how to properly and efficiently micro-manage memory alocation and memory transfers has never been quite low ;).

GCC for the R5900i (which started from GCC 2.95) is hardly "advanced" (it SUCKS in the words of MANY developers and some SCE engineers as well) and for peak performance understanding how things work at the very low level and all the quirks of the hardware is needed: you can rant about advanced C/C++ features, but I am not sure tons of lines of evolved and high level C/C++ code ill help the poor souls that have to create an optimized ASM version of that giant mess.

I know what you want to say, but the answer to your rage against such "poopy" practices is the one Naughty Dog showed (it should be pushed further on PlayStation 2): write your own high level language and your own compiler, libraries and tools :).

PlayStation 3 , I am talking about the SCE camp here, will surely pack MUCH better compilers and tools than what PlayStation 2 programmers have delat with (thanks mainly to IBM''s leadership in the CELL joint-venture). Still, there will be people that will micro-manage stuff to levels that would make you puke ;).
 

Bishman

Member
maharg said:
You know what, I was going to rant about this, because I personally feel that it's completely wrong in so many ways, but I'm not going to because I've already used up my quota of advanced C++ technique evangelism for the year. I'm trying to cut down ;P



Being new, the *right way* to create dynamic arrays in C++ for you is vector<>, NOT new and delete. C++ is not java. C++ in fact only bears a superficial resemblence to Java. The appropriate techniques for each language are not the same and you should not attempt to keep the superficial resemblence at the expense of using the language correctly.

Even in games, the need to manually manage memory to the extreme that is often presented as correct is decreasing all the time as developers catch up to compiler improvements. A lot of studios are still stuck with older compilers because that's what the platform supports, but the studios that are moving up are by and large using more advanced techniques.

Drop this tutorial and go get a good book on C++. Accelerated C++ is excelent and relatively short and cheap ($20 on amazon, I believe). The C++ Programming Language, written by the creator of the language, is also very good though much less introductory.

Do yourself a favour and do that, because the job market for C++ programmers who think they understand memory management but don't is going to shrink rapidly as C++ programs have to compete ever more with languages that take care of it for you. You can *easily* have nearly the level of ease of memory management in C++ as you're used to in Java if you just pick up a good book on the subject and use the right libraries.

(this was not an advanced C++ rant, and as such does not count under the above quota. Things like vector<> and other parts of the standard library are no longer advanced topics and should not be treated as such)

I am trying to make a simple 3D game with a couple friends. I am learning C++ from www.gametutorial.com. Do you think I should drop it and pick up a real C++ book? Let me add, trying to make a game before I get to UAT.
 

Ecrofirt

Member
another set of quick vector questions.

About the Rat newRat part: is newRat a function you've made, or is it something built into the vecto automatically like clear()?

What do I do if I want to use a constructor that accepts arguments (like say, the location of a player for a bullet vector)?
 

RiZ III

Member
Your asking me right? If you are,

newRat is just an object of type Rat.

So in that case, Rat doesn't have a constructor that takes in any parameters. If you want that, its just like a function.

Code:
class Rat 
{
private:
int health, power;

public:
Rat(int H, int P);  //theres a couple of ways to implement this, I'll show the simpelist

};

//note a constructor has no return type
Rat::Rat(int H, int P)
{
      health = H;
      power = P;

}

void main()
{
Rat newRat(101, 10); //so now you have a Rat object that has its members initialized

}
 

Ecrofirt

Member
Oh, haha. Yea, I think having the vector stuff in there screwed me up. No idea why I didn't realize newRat was an object :-\

So anyway, are there any books you guys would recommend? I'm looking to get started with C++ via a game route. I'm not overambitious, I'm looking to to very simple 2D stuff (probably with SDL initially, as it's very quick and easy to pick up). Things like the vector and stack are very good to learn, though, and I'd like to get started with things like that.
 

RiZ III

Member
Game route or no game route, you have to learn the basics of the language first. Only thing games really add is a lot of math, graphics, and pain.

Make sure your comfortable with pointers. Pointer arithmatic, messing with memory, and eventually get good at designing object oriented code because it reads and works much better imo.

Books.. hmm. I'm not sure what books are good. Theres a lot of tutorials online for c++. I took some classes at community college during high school too.
 

Ecrofirt

Member
ok, I think I know what I meant last night. I was half asleep, so don't mind that.

What I was wondering about was the vRats.Handle thing. Now what I would imagine is Handle is a function of the object, not of the vector. Basically what I'm saying is if my class file were this:

Code:
RAT::Move()
{
 xLocation+=1;
}

would I be able to do vRate[whateverNumber].Move(), and have it work like if I normally did this:

Code:
Rat rat1;

rat1.Move();

?

That's just what I'm wondering.

Also, I've got another quick question, but I've got to head home from college now, so i'll ask when I get back.
 

maharg

idspispopd
I already suggested two books.

graham said:
Drop this tutorial and go get a good book on C++. Accelerated C++ is excelent and relatively short and cheap ($20 on amazon, I believe). The C++ Programming Language, written by the creator of the language, is also very good though much less introductory.

And the answer is yes, you can.
 

Ecrofirt

Member
bumping again, and I've now got another quick vector question.

OK, you can only pop the back element of the vector.

I notive there's the swap method, which looks like it'll swap two elements, but I'm unsure how to use it.

What I want to do is swap the first element with the last one.

Here's my vector:


Code:
vector<FIREBALL> vFireball;

FIREBALL newFireball;

vFireball.push_back(newFireball);


/*...
...
at some point, a fireball will hit the end of the screen, or an enemy, and I'll have to pop it. By this time, it's no longer the last element, and I need to swap it with the last one in order to delete it*/

vFireball.swap(??);
vFireball.pop_back();
 

Lathentar

Looking for Pants
Use a linked list. Problem solved.

Unless of course you can give me a valid reason not to use a linked list.
 

slayn

needs to show more effort.
are pointers not taught well/avoided in general or something?

in my first C++ class in highschool something like 3 weeks in we started learning pointers with an intro somethign along the lines of, "ah pointers... you'll be using these guys s a lot. There are only two possible ways to use pointers. Either they are your bitch or you are theirs. So learn to make them your bitch."

And since then every C++ class I've ever been in has relied on fairly heavy pointer usage. In job interviews I've also been asked a decent amount about pointers/memory management but never about standard classes (though I have used em) like vector. They don't even expect you to have heard of them (at least at the companies I've talked to at our job fairs and such.)
 

slayn

needs to show more effort.
Ecrofirt said:
bumping again, and I've now got another quick vector question.

OK, you can only pop the back element of the vector.

I notive there's the swap method, which looks like it'll swap two elements, but I'm unsure how to use it.

What I want to do is swap the first element with the last one.

Here's my vector:


Code:
vector<FIREBALL> vFireball;

FIREBALL newFireball;

vFireball.push_back(newFireball);


/*...
...
at some point, a fireball will hit the end of the screen, or an enemy, and I'll have to pop it. By this time, it's no longer the last element, and I need to swap it with the last one in order to delete it*/

vFireball.swap(??);
vFireball.pop_back();

been a while since I used vector but wouldn't this work? A pop deletes the value and reads it. If you need to read the first element use:
vFireball[0];

then to delete the first element:
vFireball.erase(vFireball.begin());
 

Lathentar

Looking for Pants
slayn said:
been a while since I used vector but wouldn't this work? A pop deletes the value and reads it. If you need to read the first element use:
vFireball[0];

then to delete the first element:
vFireball.erase(vFireball.begin());

Yeah that would work, but when you delete from the front of a vector the remaining elements are then copied and shifted to the left by 1. Its a linear time delete, instead of constant time.

Using a linked list would solve this problem. Constant time insertion and deletion! Also, since you'll more than likely never need random access, a linked list is the way to go. Collisions in a real time game are far too random so being able to delete fireballs from the middle of a list fast is important and easier to understand than swap then pop.
 

RiZ III

Member
What your doing would work fine I guess. If you use a list<> instead of vector<>, then you can delete at any point in the thing because a list is a doubly linked list. But with a list<>, random access aka [] is slow. But if you aren't using subscripts, then use list<> instead. Or ofcourse you could use a linked list as someone suggested, but that has a downfall as well. You would need to be making calls to "new" a whole lot if your using this for something like bullets. Allocating memory every frame is a bad idea, cause its slow. So youd have to make a memory manager. I dont think you want to do that. I suggest you go ahead and use either vector<> or list<>.

Edit: And yes you can delete anywhere in a vector as well, but its slow.
 

Ecrofirt

Member
this c++ project is a learning experience for me. As I program this, I'm learning.

As such, I'm using vectors, which were recommended earlier in this thread.

from what I've read about vectors, you can only pop the last element in them. With my program, the last element is not always the one that has to be popped.

From what I've read, I should swap the positions of the one that needs to be popped with the back one, and then I can use pop_back(). Here's a quote right from the guide I'm using for vectors:

Code:
	// Let's say we want to get rid of some items in our list.
	// To do that we call pop_back().  This destroys the item
	// on top of the list (The last one added on) like a stack does.
	// If we didn't just want the top one removed, we would then
	// just swap the one we wanted removed with the last one in the list,
	// then call pop_back().  Neat huh :)

however, this guide doesn't go into the details of swapping. There is a swap method that's part of vector, and I would imagine this is what's used to swap their positions. This is what I'd like to use for my current project, but I'm unable to find a good deal of information about it for free online.

If someone could profide an example, it would help.
 

Ecrofirt

Member
RiZ, thanks for the reply.

I'm using vector now, and I've got it working just fine for what I need. I just need to know how to go about swapping positions, so I can get it completely working.
 

Lathentar

Looking for Pants
Ecrofirt said:
this c++ project is a learning experience for me. As I program this, I'm learning.

As such, I'm using vectors, which were recommended earlier in this thread.

from what I've read about vectors, you can only pop the last element in them. With my program, the last element is not always the one that has to be popped.

From what I've read, I should swap the positions of the one that needs to be popped with the back one, and then I can use pop_back(). Here's a quote right from the guide I'm using for vectors:

Code:
	// Let's say we want to get rid of some items in our list.
	// To do that we call pop_back().  This destroys the item
	// on top of the list (The last one added on) like a stack does.
	// If we didn't just want the top one removed, we would then
	// just swap the one we wanted removed with the last one in the list,
	// then call pop_back().  Neat huh :)

however, this guide doesn't go into the details of swapping. There is a swap method that's part of vector, and I would imagine this is what's used to swap their positions. This is what I'd like to use for my current project, but I'm unable to find a good deal of information about it for free online.

If someone could profide an example, it would help.

I think what you want is just std::swap(vFireball[x], vFireball[y]);

Then you need to make sure to write the equal operator for your Fireball class. (If I remember correctly)
 

Ecrofirt

Member
when I try that, I get:
error C2660: 'std::vector<_Ty>::swap' : function does not take 2 arguments
with
[
_Ty=FIREBALL
]
 

RiZ III

Member
Ah actually now that I look at the documentation for swap, I believe it is used to swap the data of one vector to another. So yea, you don't want to use that. Once again I suggest list<>, however if you don't want to do that, you can still delete from the middle of the vector<>, but if you are doing it in a loop, you have to be careful. You can just use the erase member function.

edit: Right, swap only takes one parameter which is another vector. It will swap all the data from that vector you pass in. So you don't want to use swap here.
 

Ecrofirt

Member
ah, thanks RiZ. That answers my question.

check your PM box in a few minutes, i've got a quick college question for you
 
Status
Not open for further replies.
Top Bottom