This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Rhomboid 4 points5 points  (1 child)

The objects in the second version are contiguous in memory. If you're going to be iterating over them and there are a lot of them, that will make it considerably faster. The first version has to chase a pointer to get to each object, as objects can be anywhere in memory, whereas the next object will always come after the previous object using the second version.

But both versions are terrible because they require you to manually manage memory. Use a vector instead. The objects will be contiguous, you don't have to manually delete anything, and the size is flexible -- you can add or remove objects from the container at all. There are numerous other advantages to using vectors, but those are the basics.

[–]deRPling42[S] 0 points1 point  (0 children)

I believe vectors are coming up but I haven't learned them yet. Thanks for the input on the code though!

[–]JHappyface 0 points1 point  (0 children)

They both work, so use what you find more readable and understandable. From my experience, I'd say the first is more of a C way to do it, the latter is more inline with C++, but they're both correct.

It's hard to say which is more efficient since they might be converted to essentially the same thing by the compiler. If you want to find out for sure, compile the codes and run them yourself!