Hello everyone. I have a problem, but it seems to me that it is just a question of semantic. I missed something in my expression. I am trying to populate directly an array with some Vector2. In the code below, I use a bad method so as to get all my Vector2 in a single array. It works as expected, but I guess that there is a better way. Thank you for your help ++
PS : I am developing a program using the OLC PixelGameEngine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// here there are my Vector2 as float
olc::vf2d vS1 = { 100.0f, 100.0f };
olc::vf2d vS2 = { 200.0f, 150.0f };
olc::vf2d vS3 = { 100.0f, 200.0f };
std::unique_ptr<olc::vf2d[]> allObj = nullptr;
(...)
OnUserCreate()
{
allObj = std::make_unique<olc::vf2d[]>(3); // three entries
allObj[0] = vS1; // populate the array using index :/
allObj[1] = vS2;
allObj[2] = vS3;
}
Well, normally you don't need to use new when working with unique_ptr but I don't think this kind of direct list initialization is possible with make_unique, that's why I had to use new. Normally I would prefer make_unique if possible.
sizeof(allObj) gives you the size of the unique_ptr object. Since it probably just contains a pointer inside it's essentially giving you the size of a pointer. This is not very useful.
There is no way to get the size of an array if all you've got is a pointer to the first element. I wasn't thinking about that when I wrote my previous post. I guess that makes it a bad idea to leave out the size.
Something like the following would be less error prone:
Unfortunately this means you need to keep N and the number of elements that you initialize the array with in sync but at least it will give you a compilation error if N is less than the number of elements that you use to initialize the array. If N is larger it gives you additional value-initialized elements which is probably not what you want but quite harmless.
I usually don't see unique_ptr used for arrays that often. It's usually easier to simply use std::vector. Is that something you've considered?
Ok. I understand now. Thank you for your explanations. I though that sizeof(anArray) was llike anArray.Length in C#. I would like to use it so as to manage all Vector2 in a single loop. I wrote a AABB collison system using sizeof() as a way to get all elements in my array. Now I understand why it doesn't work - and why I have as output 8 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// simple checker AABB for sprites
bool AABB(gck::vi2d a)
{
for (int o = 0; o < sizeof(allObj); o++)
{ // a tip which I used to avoid "bad" entries
if (allObj[o].x == 0 && allObj[o].y == 0)
break;
float resultAA = a.x - allObj[o].x;
float resultBB = a.y - allObj[o].y;
if (fabs(resultAA) < size * ratio && fabs(resultBB) < size * ratio)
returnfalse;
}
returntrue;
}
Changed for std::vector<olc::vf2d> allObj{ ... };
Thank you for your help.