Dynamic arrays inside of classes in Object Pascal

0 like 0 dislike
6 views
How to describe inside a class of dynamic array?

You need something like this:
type
myclass = class
private
n: integer;
a: array[0..n] of integer;
public
constructor create(n_ : integer);
end;


This code swears that it is not n — not described.
by | 6 views

3 Answers

0 like 0 dislike
a: array of integer;
then you can use the SetLength(a, n);
\r
I did it in Delphi, ObjectPascal should be the same...
by
0 like 0 dislike
Object Pascal is very sad working with dynamic arrays.
\r
Much better and, importantly, faster in terms of execution of the code will use string.
\r
And then getter and setter to drag/assign the elements.
\r
Ie
a: string;
\r
designer setlength(a, n*4) (*8 if a 64 bit application)
\r
and methods
getElement(x:integer)
var tmpInt:integer;
move(a[(x*4)+1], tmpInt, 4); (8 64 bit)
result:=tmpInt;
\r
setElement(x, value:integer)
var tmpInt:integer;
tmpInt:=value;
move(tmpInt, a[(x*4)+1], 4); (everywhere 8 to 64 bits)
\r
It is, at first glance, more complicated than the previous answer, but in fact the problems will be less. With gears as parametrov to the function, using inside other functions, etc.
by
0 like 0 dislike
To describe the dynamic array inside the class is easy. In advance
type
TIntegerArray = array of Integer;
TMyClass = class
private
FMyIntegers: TIntegerArray;
end;
\r
But within the class dynamic array is needed as a fifth leg to a dog. It is good for passing values to functions and return them from there. Inserting, deleting, sorting, searching elements to a dynamic array will be first terribly inefficient, and secondly- with the inability easy replacement with another container.
For everything else, much better than the normal container class, for example, TIntegerArrayList from JCL.
by

Related questions

0 like 0 dislike
4 answers
0 like 0 dislike
4 answers
0 like 0 dislike
2 answers
0 like 0 dislike
3 answers
asked May 21, 2019 by d1ret
110,608 questions
257,186 answers
0 comments
1,119 users