On 30.11.2016 12:36, Ryan Joseph wrote:
>
>
>> On Nov 30, 2016, at 6:24 PM, Graeme Geldenhuys
>> <[email protected]> wrote:
>>
>> What would you iterate/enumerate in that? I can understand iterating an
>> "array of TMyRec", but not TMyRec itself.
>
> I have a dynamic array inside a record. I’m using a record instead of a class
> because I want it to be stored on the stack. It’s trivial to just enumerate
> the array inside the record but I wanted to try the more elegant solution of
> making an enumerator for the record.
I've attached an example that shows how this *can* be done (it's not the
only way to do this however).
Regards,
Sven
program trecenum;
{$mode objfpc}
type
TLongIntArray = array of LongInt;
TRec = record
arr: TLongIntArray;
end;
TRecEnumerator = object
private
fArr: TLongIntArray;
fIndex: Integer;
function GetCurrent: LongInt;
public
constructor Create(aArr: TLongIntArray);
function MoveNext: Boolean;
property Current: LongInt read GetCurrent;
end;
constructor TRecEnumerator.Create(aArr: TLongIntArray);
begin
fArr := aArr;
fIndex := -1;
end;
function TRecEnumerator.GetCurrent: LongInt;
begin
Result := fArr[fIndex];
end;
function TRecEnumerator.MoveNext: Boolean;
begin
Inc(fIndex);
Result := fIndex < Length(fArr);
end;
operator enumerator(r: TRec): TRecEnumerator;
begin
Result.Create(r.arr);
end;
var
r: TRec;
i: LongInt;
begin
r.arr := TLongIntArray.Create(42, 53, 96, 29);
for i in r do
Writeln(i);
end.
_______________________________________________
fpc-pascal maillist - [email protected]
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal