Developers Club geek daily blog

1 year, 10 months ago
It is transfer of the article "Associative arrays" published on January 1, 2016. On my taste article is a little excessively superficial and does not contain a large number of details, but it can be useful that who is familiar with associative arrays in other programming languages.

In language D there is a built-in support of the associative arrays also known as a hash table.
They are similar Map in Java or std::unordered_map in C ++.

Declaration of associative array



To declare associative array, use the following syntax:

// Прим. перев.: value — тип значения, key — тип ключа
value[key] myAssociativeArray;



Insert of elements in associative array


For an insert of elements in associative array use the operator [].
Below the example of creation of associative array of squares of integral numbers from 0 to 10 and their output to the screen is given.

import std.stdio;

void main()
{
    int[int] squares; // Объявление

    for (int i = 0; i <= 10; ++i)
        squares[i] = i * i; // Вставка в ассоциативный массив

    writeln(squares);
}


Having started an example, we will receive the following output:
[0:0, 6:36, 7:49, 2:4, 3:9, 10:100, 1:1, 8:64, 5:25, 4:16, 9:81]
Pay attention that numbers are not sorted - it is it is expected: associative arrays internally are not sorted.
Notes:
  • Reassignment of the existing key will replace value.
  • Attempt to address a nonexistent key will lead to an error core.exception.RangeError.


Removal of elements from associative array


For removal of elements from associative array use function remove().

aa.remove("hello");


Check on existence of a key


For check of a key on existence use the operator in, which returns the pointer on value. If the key does not exist, the pointer will be null.

int[int] squares;

// ...

int* p = 10 in squares;
// Прим. перев.: Не проверяйте на null операторами сравнения, используйте is
if (p !is null)
    writeln(*p);
else
    writeln("Нет значения.");


Cleaning of associative array


There are two methods to clear associative array:
  1. To walk on keys and to delete them
  2. To discard an old array and to create new


Method 1: we delete keys


foreach (key; aa.keys)
    aa.remove(key);


Method 2: we create a new array


To throw out the existing array, appropriate it value null.

aa = null; // помечено для сборки мусора
aa[1] = 1; // записано по новому адресу в памяти


Properties


We are already familiar with some properties of associative arrays, for example remove() or keys. The others are included below:
Property Description
.sizeof Returns the size of the link to associative array. In 32-bit assemblies it is 4, and in 64-bit assemblies 8.
.length Returns amount of values in an array. Unlike dynamic arrays, this property only for reading.
.dup Creates associative array of the same size and copies in it contents of the first array.
.keys Returns a dynamic array which elements are keys of initial associative array.
.values Returns a dynamic array which elements are values of initial associative array.
.rehash On site will reorganize an array, optimizing search in it. rehash it is useful, for example, when in the program the table of characters according to which afterwards it is necessary to run for search is loaded. Returns the link to the reorganized array.
.byKey() Returns the range suitable for search by means of a cycle foreach keys of associative array.
.byValue() Returns the range suitable for search by means of a cycle foreach values of associative array.
.byKeyValue() Returns the range suitable for search by means of a cycle foreach steam key value of associative array. The returned couples are presented in the form of opaque type with properties .key and .value, allowing to address respectively a key and value of couple.
.get(Key key, lazy Value defVal) Looks for a key key. If it exists, returns the value corresponding to it; if does not exist, fulfills and returns value by default defVal.


What else to esteem


For more detailed information (for example to learn about work with classes and structures in associative arrays) address official documentation on dlang.org.

This article is a translation of the original post at habrahabr.ru/post/274723/
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here: sysmagazine.com@gmail.com.

We believe that the knowledge, which is available at the most popular Russian IT blog habrahabr.ru, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.
Best wishes.

comments powered by Disqus