Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Finding an objects location in an array

23 views
Skip to first unread message

sp...@potato.field

unread,
May 9, 2017, 9:34:49 AM5/9/17
to
Hi

I was wondering if its possible for an object constructor to be passed its
position in an array. eg:

class my_class
{
:
:
} myarray[10][20];

Is there a way for each individual object to find its x,y location? Obviously
I can just declare **myarray then do a load of messy manual allocation passing
the x,y to the constructor at "new", but perhaps the 2011 or 2014 standards
have added automated this at all? Or is there some STL trick that can achieve
this using a container?

Thanks for any help

--
Spud

Alf P. Steinbach

unread,
May 9, 2017, 10:18:07 PM5/9/17
to
For a raw array all that you have to work with is the default
constructor, and all that it knows about the object it's initializing,
is its address.

If, however, it has available the start address of the array, a pointer
to first item in the array, then it can compute its array index.

This means a class that's not usable as anything but array item. But
maybe it can be done as templated wrapper for the "real" array item class.

* * *

An alternative is to just define a factory function that first creates
the array, and then loops over all items, passing them the item index.


Cheers & hth.,

- Akf

sp...@potato.field

unread,
May 10, 2017, 4:30:08 AM5/10/17
to
On Wed, 10 May 2017 04:17:59 +0200
"Alf P. Steinbach" <alf.p.stein...@gmail.com> wrote:
>An alternative is to just define a factory function that first creates
>the array, and then loops over all items, passing them the item index.

Sure, I mean writing 2 loops and manually creating the objects and passing
them their location isn't hard, but initialising arrays of objects is so common
I wondered if buried somewhere in the latest standards there was some special
constructor that would be passed the array location of the object.

Since they've thrown in so much other rubbish into 2011 and 2014 which barely
anyone will ever use I imagine this would have been a useful addition.

--
Spud


sp...@potato.field

unread,
May 10, 2017, 7:14:40 AM5/10/17
to
On 10 May 2017 09:32:28 GMT
r...@zedat.fu-berlin.de (Stefan Ram) wrote:
>sp...@potato.field writes:
>>I was wondering if its possible for an object constructor to be passed its
>>position in an array. eg:
>>class my_class
>>{
>> :
>> :
>>} myarray[10][20];
>>Is there a way for each individual object to find its x,y location?
>
> Here's my quick take at it:

Its certainly an interesting method, but its not exactly clean and simple and
having to hard code the arry dimensions into the code rather defeats the
point :) Also shouldn't "entry->major = i / 20u" be "i / 10u"?

--
Spud

0 new messages