D language array (2)

xiaoxiao2021-03-06  45

Set up the length of the dynamic array of dynamic arrays

The .length attribute can be used as the left value of the = operator:

Array.Length = 7;

This causes arrays to be redistributed in place, and existing content is copied into a new array. If the new array is shorter than the original array, only those content that can be accommodated. If the new array is longer than the original number of groups, the portion of the new number of groups will fill the default initial value of the elements.

In order to achieve the highest efficiency, the runtime is always trying to properly adjust the size of the array to avoid additional replication. If the array is not assigned by the New operator or the last Resize operation, and the new array is larger than the original number group, it will always be replicated when running.

This means that if some slices depend on array to be reset, the new array may overlap with the slice, that is,:

CHAR [] a = new char [20];

Char [] b = a [0..10];

Char [] c = a [10..20];

B.Length = 15; // Always reset the size, because it is a slice on a [],

// and A [] length is greater than 15

B [11] = 'x'; // a [15] and C [5] also affected

a.length = 1;

a.length = 20; // memory distribution has not changed

C.Length = 12; // Always copy, because c [] does not at the beginning of the block allocated by GC

C [5] = 'y'; // does not affect the content of A [] and B []

A.Length = 25; // may also not copy

A [3] = 'z'; / / may not affect B [3], B [3] still with the original A [3] overlap

If you want to make a copy, use the .dup property, you will get a separate array that can be resize.

These discussions are equally applicable to connection operations that use ~ and ~ = operator.

The size of the reset dynamic array is a relatively expensive operation. So, although the following method for filling arrays is correct:

array;

While (1)

{c = getInput ();

IF (! c)

Break;

Array.Length = array.length 1;

Array [array.length - 1] = C;

}

Its efficiency is not high. A more practical approach is to minimize the use of Resize operations:

array;

Array.Length = 100; // Guess

For (i = 0; 1; i )

{c = getInput ();

IF (! c)

Break;

IF (i == array.length)

Array.Length = array.length * 2;

Array [i] = C;

}

Array.Length = I;

Choosing a good guess is an art, but usually you can find a value for 99%. For example, when collecting user input from the console, the length is less likely to exceed 80.

Array Crossing Inspection If a number of numbers that are less than 0 or greater than or equal to the array length is an error. If the subscript is subscribed, if it is detected by runtime, an ArrayboundSerror will throw an exception; if it is detected when compiling, an error will be generated. The program should not depend on the array crosstalk exception check, for example, the method of the following program is wrong: TRY

{

For (i = 0;; i )

{

Array [i] = 5;

}

}

Catch (ArrayboundSerror)

{

// Terminate the cycle

}

The correct way of writing is:

For (i = 0; i

{

Array [i] = 5;

}

Realize the notation: The compiler should try to check the array of crossed errors when compiling, for example:

Int [3] foo;

INT x = foo [3]; // Error, the offline should be able to decide whether to insert a dynamic array croucher check code at compile time.

Array initialization

The pointer is initialized to NULL. The content of the static array is initialized to the default initial value of the array element type. Dynamic arrays are initialized to have 0 elements. The associated array is initialized to have 0 elements.

Static initialization of static arrays

INT [3] a = [1: 2, 3]; // a [0] = 0, A [1] = 2, A [2] = 3

This method is the most convenient when identified as an enumeration type under the array:

Enum color {red, blue, green};

INT Value [color.max] = [Blue: 6, Green: 2, Red: 5];

If there are array members being initialized, all members must be initialized. This is used to capture a common error: a new element is added to the enumeration type, but the initialization list of static instances of the array of enumerated arguments has been updated.

Special array type

Bit population can construct a group:

Bit [10] X; // 10 digits

The actual storage is dependent on implementation.

Remarks: On the Intel CPU, you should follow 32.

x.length // 10, bit number

X.Size // 4, the number of bytes used

As shown above, the size of each element is not (x.size / x.length)

.

String languages ​​should be good at handling strings. C and C are not good at this. The main difficulties are memory allocation, handling temporary objects, always need to scan strings to find endfill 0 and fixed array lengths.

Dynamic arrays in D provide an obvious solution - string is a dynamic array of characters as elements. The string of string is a simple method of writing a word array.

CHAR [] STR;

CHAR [] str1 = "abc";

CHAR [] string uses UTF-8 format. Wchar [] string uses the UTF-16 format. DCHAR [] string uses UTF-32 format.

Strings can use obvious semantic replication, comparison, connection, and append:

STR1 = STR2;

IF (STR1

FUNC (STR3 ~ STR4);

STR4 ~ = STR1;

All generated temporary objects are reclaimed by the garbage collection program (or use alloca ()). Moreover, this is applicable to all arrays, not just the array of strings.

You can use a pointer to CHAR:

Char * p = & str [3]; // point to the fourth element

Char * p = str; // point to the first element

However, since the string array in D is not terminated by 0, if you want to pass a string pointer to C, you should add 0: STR ~ = "/ 0";

The type of string is determined in the compiled semantic analysis phase. The type is one of the following: char [], wchar [], dchar [], and decided by implicit conversion rules. If there are two available modes of conversion, it is considered an error. In order to avoid this ambiguity, type conversion should be used:

Cast (wchar []) "ABC" // This is a Wchar character array

If needed, string text is implicitly converted between char, Wchar, and DCHAR.

The length of the length can be converted to CHAR, WCHAR or DCHAR constant:

Char C;

Wchar W;

DCHAR D;

C = 'b'; // C is assigned to Char characters 'b'

W = 'b'; // W is assigned Wchar characters 'b'

W = 'bc'; // error - only one Wchar character can be used

W = "b" [0]; // W is assigned to Wchar characters 'b'

w = '/ r'; // W is assigned to Wchar characters "Enter"

D = 'd'; // D is assigned DCHAR characters 'D'

Printf () and strings

Printf () is a C function that is not part of D.

Printf () outputs a C string terminating at 0. Two types

Printf () Outputs the method of d string. The first method is to add a terminated 0 and convert the result to a char *:

STR ~ = "/ 0";

Printf ("THE STRING IS '% S' / N", (CHAR *) STR);

The second method uses a precision indicator. The memory distribution of the D array is: array length, string, so this method can work:

Printf ("the string is '%. * s' / n", str);

In the future, it may be

Printf () Add a new format indicator instead of this method that relies on the details.

Implicit conversion pointer

T * can be implicitly converted to the following things:

U *, where u is the base class of T. Void * static array

T [DIM] can be implicitly converted to one of the following:

T * t [] u [DIM], where u is the base class of T. U [], where u is the base class of T. U *, where u is the base class of T. Void * void [] Dynamic array

T [] can be implicitly converted to one of the following:

T * u [], where u is the base class of T. U *, where u is the base class of T. Void *

The associated array D go further on the array - joins the associated array. The subsidiary of the associated array is not necessarily an array, therefore has a wide range of purposes. Related array subscript is called

Keyword.

In the declaration of the associated array, the type declaration of the keyword is located in []:

INT [char []] b; // Related array B with INT as array elements, subscript as a character array

B ["Hello"] = 3; // Set the value of the keyword "hello" corresponding to 3

Func (B ["Hello"]); / / Parameters pass to FUNC () 3

You can use the Delete operator to delete a key value in the associated array: Delete B ["Hello"];

This is easy to make mistakes to delete the value of B [Hello ", but in this way, this operation is just deleted from the associated array" Hello ".

In expression returns a boolean value representing whether the keyword is in an associated array:

IF ("Hello" in b)

...

The type of keyword cannot be a function or void.

Attributes of the attribute association array are:

SIZEOF returns the size of the reference to the associated array; the typical value is 8. Length returns the number of value in the associated array. Unlike dynamic arrays, it is read-only. Keys Returns the dynamic array, and the elements of the array are keywords for associated arrays. VALUES Returns the dynamic array, the element of the array is the value of the associated array. Rehash is properly reorganized to associate arrays to improve lookup efficiency. For example, the program has already loaded a symbolic table and will start a lookup, and Rehash will increase efficiency. Returns a reference to the new array.

Associated array example: word count

Import std.file; // d file I / O

Int main (char [] [] args)

{

Int word_total;

INT line_total;

int CHAR_TOTAL;

Int [char []] DICTIONARY;

Printf ("Lines Words Bytes File / N);

For (int i = 1; i

{

CHAR [] INPUT; / / Input buffer

INT W_CNT, L_CNT, C_CNT; // Word, Line, CHAR count

INT INWORD;

Int wstart;

INPUT = std.file.read (args [i]); // Read file into input []

Foreach (Char C; Input)

{

IF (c == '/ n')

l_cnt;

IF (c> = '0' && c <= '9')

{

}

ELSE IF (c> = 'a' && c <= 'z' ||

C> = 'a' && c <= 'z')

{

IF (! inword)

{

Wstart = j;

INWORD = 1;

w_cnt;

}

}

Else if (inword)

{

CHAR [] Word = INPUT [WSTART .. J];

Dictionary [Word] ; // incrementing Word count

INWORD = 0;

}

C_CNT;

}

IF (inword)

{

Char [] word = INPUT [WSTART .. Input.length];

Dictionary [Word] ;

}

Printf ("% 8LD% 8LD% 8LD%. * S / N", L_CNT, W_CNT, C_CNT, ARGS [I]);

LINE_TOTAL = L_cnt;

Word_total = w_cnt;

CHAR_TOTAL = C_CNT;

}

IF (Args.Length> 2)

{

Printf ("-------------------------------- / n% 8LD% 8LD% 8LD Total , Line_Total, Word_Total, Char_Total;

}

Printf ("-------------------------------- / n");

Char [] [] keys = Dictionary.keys; / / Find all words in Dictionary []

For (int i = 0; i

{

CHAR [] WORD;

Word = keys [i];

Printf ("% 3D%. * S / N", Dictionary [Word], Word);

}

Return 0;

}

转载请注明原文地址:https://www.9cbs.com/read-55560.html

New Post(0)