If you work with php you can see the php have associative array (or array width string key) in programing lang.
For example:
$server['hostname'] = 'localhost';
$server['database'] = 'test';
$server['username'] = 'root';
$server['password'] = 'password' ;
// 2d array
$all['myserver']['hostname'] = 'localhost' ;
But can't find any default way to use associative array in delphi.
First I want find default way with out any output component or class .
Second if really I cant find with internal way I force choose output classes only.
I use Delphi XE3 , many thanks for your help.
edit:
I found one class here : http://www.delphipages.com/forum/showthread.php?t=26334
same as php , but any better way?
You can use TDictionary<string,string> from the Generics.Collections unit.
var
Dict: TDictionary<string,string>;
myValue: string;
....
Dict := TDictionary<string,string>.Create;
try
Dict.Add('hostname', 'localhost');
Dict.Add('database', 'test');
//etc.
myValue := Dict['hostname'];
finally
Dict.Free;
end;
And so on and so on.
If you want a dictionary that contains a dictionary, you can do use TDictionary<string, TDictionary<string,string>>.
However, when you do that you'll need to take special care over the lifetime of the dictionary items that are contained in the outer dictionary. You can use TObjectDictionary<K,V> to help manage that for you. You'd create one of these objects like this:
TObjectDictionary<string, TDictionary<string,string>>.Create([doOwnsValues]);
This TObjectDictionary<k,V> operates the same was as a traditional TObjectList with OwnsObjects set to True.
You can use tStrings and tStringList for this purpose, but 2d arrays are out of the scope of these components.
Usage;
var
names : TStrings;
begin
...
names := TStringList.Create;
...
...
names.values['ABC'] := 'VALUE of ABC' ;
...
...
end ;
I had solved the problem that simple way (example):
uses StrUtils;
...
const const_TypesChar : array [0..4] of String =
(
'I',
'F',
'D',
'S',
'B'
);
const const_TypesStr : array [0..4] of String =
(
'Integer',
'Float',
'Datetime',
'String',
'Boolean'
);
...
Value := const_TypesStr[ AnsiIndexStr('S', const_TypesChar) ];
// As an example, after execution of this code Value variable will have 'String' value.
//
Then in program we are using two arrays const_TypesChar and const_TypesStr as one associative array with AnsiIndexStr function.
The plus is that it's simple and that we don't need to change code in different places in program every time when we add elements to our arrays.
Look at ArrayS. You can use associative arrays which stores predefined type of data (integer, string, boolean, float), or any of them. For example, below I define an associative array of floats:
uses ArrayS;
var floats : IFltArray;
floats := CreateArray;
floats['first'] := 0.1;
floats['second'] := 0.2;
writeln( floats['second'] );
And so on.
Updated at 2020-03-15
Zipped source code
Ussage example in Russian
Related
Say i have
ArrayOfTXSDecimal = array of TXSDecimal;
Then during runtime i do
Ids := ArrayOfTXSDecimal.create(14450);
What did i just create? an array(ids) with 14450 indexs or just index 14450
You are creating a dynamic array with one element whose value is 14450. You are doing the equivalent of this:
SetLength(Ids, 1);
Ids[0] := 14450;
This Create() syntax for dynamic arrays is documented on Embarcadero's DocWiki:
An alternative method of allocating memory for dynamic arrays is to invoke the array constructor:
type
TMyFlexibleArray = array of Integer;
begin
MyFlexibleArray := TMyFlexibleArray.Create(1, 2, 3 {...});
end;
which allocates memory for three elements and assigns each element the given value.
I am fairly new to Go. I have coded in JavaScript where I could do this:
var x = [];
x[0] = 1;
This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.
I did this:
var x []string
x[0] = "name"
How do I accomplish that?
When you type:
var x []string
You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.
A few examples of how you can do it:
x := []string{"name"} // Creates a slice with length 1
y := make([]string, 10) // Creates a slice with length 10
y[0] = "name" // Set the first index to "name". The remaining 9 will be ""
var z []string // Create an empty nil slice
z = append(z, "name") // Appends "name" to the slice, creating a new slice if required
More indepth reading about slices:
Go slices usage and internals
In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).
Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.
In your code:
var x []string
x[0] = "name"
The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.
If you know the length in advance, create your array or slice with that, e.g.:
var arr [3]string // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3
After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.
You may also use a composite literal to create and initialize the array or slice in one step, e.g.
var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"} // Slice
You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():
var x []string
x = append(x, "name")
If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:
var x = map[int]string{}
x[0] = "name"
(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)
You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.
Must read blog post about arrays and slices: Go Slices: usage and internals
Recommended questions / answers for a better understanding:
Why have arrays in Go?
How do I initialize an array without using a for loop in Go?
How do I find the size of the array in go
Keyed items in golang array initialization
Are golang slices pass by value?
Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?
In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).
As srxf mentioned, have you done the Go tour? There is a page about slices.
I found out that the way to do it is through a dynamic array. Like this
type mytype struct {
a string
}
func main() {
a := []mytype{mytype{"name1"}}
a = append(a, mytype{"name 2"})
fmt.Println(a);
}
golang playground link: https://play.golang.org/p/owPHdQ6Y6e
I want to create 2-d arrays dynamically in Perl. I am not sure how to do this exactly.My requirement is something like this-
#a =([0,1,...],[1,0,1..],...)
Also I want to name the references to the internal array dynamically. i.e. I must be able to refer to my internal arrays with my chosen names which I will be allocating dynamically.
Can someone please help me on this.
It sounds like you want a tree/hash of arrays. Use references to achieve this.
Example of hash of array of array:
$ref = {};
$ref->{'name'} = [];
$ref->{'name'}[0] = [];
$ref->{'name'}[0][1] = 3;
This could be dynamic if required. Make sure you initialise what the reference is pointing at.
Example array of array references:
my #x;
$x[$_] = [0..int(rand(5)+1)] for (0..3);
You probably have some kind of loop?
for (...) {
my #subarray = ...;
push #a, \#subarray;
}
You could also do
for (...) {
push #a, [ ... ];
}
If it's actually a foreach loop, you could even replace it with a map.
my #a = map { ...; [ ... ] } ...;
I'm using Array(0, {i -> ""}) currently, and I would like to know if there's a better implementation such as Array()
plus, if I'm using arrayOfNulls<String>(0) as Array<String>, the compiler will alert me that this cast can never succeed. But it's the default implementation inside Array(0, {i -> ""}). Do I miss something?
As of late (June 2015) there is the Kotlin standard library function
public fun <T> arrayOf(vararg t: T): Array<T>
So to create an empty array of Strings you can write
val emptyStringArray = arrayOf<String>()
Just for reference, there is also emptyArray. For example,
var arr = emptyArray<String>()
See
doc
Array.kt
Empty or null? That's the question!
To create an array of nulls, simply use arrayOfNulls<Type>(length).
But to generate an EMPTY array of size length, use:
val arr = Array(length) { emptyObject }
Note that you must define an emptyObject properly per each data-type (beacause you don't want nulls). E. g. for Strings, emptyObject can be "". So:
val arr = Array(3) { "" } // is equivalent for: arrayOf("","","")
Here is a live example. Note that the program runs with two sample arguments, by default.
null array
var arrayString=Array<String?>(5){null}
var nullArray= arrayOfNulls<String>(5)
As mentioned above, you can use IntArray(size) or FloatArray(size).
I found two ways to create an empty array, the second way without a lambda:
var arr = Array (0, { i -> "" })
var arr2 = array<String>()
Regarding Kotlin's null strings, this is not allowed. You have to use String? type to allow strings to be null.
Use:
#JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
It returns an 0 size array of Strings, initialized with null values.
1. Wrong:
#JvmField val EMPTY_STRING_ARRAY = emptyArray<String>()
It returns arrayOfNulls<String>(0)
2. Wrong:
#JvmField val EMPTY_STRING_ARRAY = arrayOf<String>()
It returns an array containing the Strings.
Simplest way to initialise array and assigning values :
val myArray: Array<String> = Array(2) { "" }
myArray[0] = "Java"
myArray[1] = "Kotlin"
Is there a way in Delphi declaring an array of strings such as following one?
{'first','second','third'}
In XE7 you can declare a dynamic array constant like this:
const
MyArray: TArray<String> = ['First','Second','Third'];
try this
Const
Elements =3;
MyArray : array [1..Elements] of string = ('element 1','element 2','element 3');
You can use dynamic arrays and try this:
var
FMyArray: TArray<string>;
function MyArray: TArray<string>;
begin
if Length(FMyArray) = 0 then
FMyArray := TArray<string>.Create('One', 'Two', 'Three');
Result := FMyArray;
end;
While this does do a run-time initialization of a dynamic array on the heap, it also shows that Delphi supports a "pseudo-constructor" on dynamic arrays that allow in-place initialization. (NOTE: the above code isn't thread-safe).
Now all you need to do to find out the length of the array, is use the Length() standard function, or to find the allowed index range, use the Low() and High() standard functions.
If you're using an older version of Delphi, replace the TArray with your own dynamic-array string type such as:
type
TStringArray = array of string;
You can do this in a indirect way. Create a function like:
procedure assignStringArray(var rasVelden: ArrayOfString; const asVeldenIn: Array Of String);
var
iLengte, iT1: Integer;
begin
iLengte := Length(asVeldenIn);
SetLength(rasVelden, iLengte);
for iT1 := iLengte-1 downto 0 do
rasVelden[iT1] := asVeldenIn[iT1];
end;
and call this function like:
assignStringArray(asVelden, ['String1', 'String2', 'String3']);
where:
asVelden: ArrayOfString;