Array Initialization: Difference between revisions

From Rosetta Code
Content added Content deleted
(<code>)
m (<lang>)
Line 7: Line 7:
=={{header|Ada}}==
=={{header|Ada}}==
The array value obtained directly from data is called array aggregate. Considering these array declarations:
The array value obtained directly from data is called array aggregate. Considering these array declarations:
<code ada>
<lang ada>
type Vector is array (Integer range <>) of Integer;
type Vector is array (Integer range <>) of Integer;
type Matrix is array (Integer range <>, Integer range <>) of Integer;
type Matrix is array (Integer range <>, Integer range <>) of Integer;
type String is array (Integer range <>) of Character;
type String is array (Integer range <>) of Character;
type Bits is array (Integer range <>) of Boolean;
type Bits is array (Integer range <>) of Boolean;
</code>
</lang>
Initialization by an aggregate using positional and keyed notations:
Initialization by an aggregate using positional and keyed notations:
<code ada>
<lang ada>
X : Vector := (1, 4, 5);
X : Vector := (1, 4, 5);
Y : Vector (1..100) := (2|3 => 1, 5..20 => 2, others => 0);
Y : Vector (1..100) := (2|3 => 1, 5..20 => 2, others => 0);
Line 22: Line 22:
L : String (1..80) := (others => ' ');
L : String (1..80) := (others => ' ');
B : Bits := not (1..2 => False); -- Same as (1..2 => True)
B : Bits := not (1..2 => False); -- Same as (1..2 => True)
</code>
</lang>
Note that the array bounds, when unconstrained as in these examples can be either determined by the aggregate, like the initialization of X shows. Or else they can be specified as a constraint, like for example in the initialization of Y. In this case '''others''' choice can be used to specify all unmentioned elements. But in any case, the compiler verifies that all array elements are initialized by the aggregate. Single dimensional arrays of characters can be initialized by character strings, as the variable S shows. Of course, array aggregates can participate in array expressions and these expressions can be used to initialize arrays. The variable B is initialized by an aggregate inversed by the operation '''not'''.
Note that the array bounds, when unconstrained as in these examples can be either determined by the aggregate, like the initialization of X shows. Or else they can be specified as a constraint, like for example in the initialization of Y. In this case '''others''' choice can be used to specify all unmentioned elements. But in any case, the compiler verifies that all array elements are initialized by the aggregate. Single dimensional arrays of characters can be initialized by character strings, as the variable S shows. Of course, array aggregates can participate in array expressions and these expressions can be used to initialize arrays. The variable B is initialized by an aggregate inversed by the operation '''not'''.
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 51: Line 51:


To assign a single value to an array, one uses the [] operator.
To assign a single value to an array, one uses the [] operator.
<code cpp>
<lang cpp>
// Assign the value 7 to the first element of myArray.
// Assign the value 7 to the first element of myArray.
myArray[0] = 7;
myArray[0] = 7;
</code>
</lang>
If '''myArray''' has ten elements, one can use a loop to fill it.
If '''myArray''' has ten elements, one can use a loop to fill it.
<code cpp>
<lang cpp>
// Assign the sequence 1..10 to myArray
// Assign the sequence 1..10 to myArray
for(int i = 0; i < 10; ++i)
for(int i = 0; i < 10; ++i)
myArray[i] = i + 1;
myArray[i] = i + 1;
</code>
</lang>
If '''myArray''' has two dimensions, you can use nested loops.
If '''myArray''' has two dimensions, you can use nested loops.
<code cpp>
<lang cpp>
// Create a multiplication table
// Create a multiplication table
for(int y = 0; y < 10; ++y)
for(int y = 0; y < 10; ++y)
for(int x = 0; x < 10; ++x)
for(int x = 0; x < 10; ++x)
myArray[x][y] = (x+1) * (y+1);
myArray[x][y] = (x+1) * (y+1);
</code>
</lang>


===STL===
===STL===
{{libheader|STL}}STL provides '''std::vector''', which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.
{{libheader|STL}}STL provides '''std::vector''', which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.
<code cpp>
<lang cpp>
myVector.push_back(value);
myVector.push_back(value);
</code>
</lang>
Like simple arrays, '''std::vector''' allows the use of the [] operator, and once an element has been added, it can be changed the same way a simple array can.
Like simple arrays, '''std::vector''' allows the use of the [] operator, and once an element has been added, it can be changed the same way a simple array can.
<code cpp>
<lang cpp>
myVector[0] = value;
myVector[0] = value;
</code>
</lang>
Unlike simple arrays, '''std::vector''' allows you to determing the size of the array. You can use this set all of the values in the array:
Unlike simple arrays, '''std::vector''' allows you to determing the size of the array. You can use this set all of the values in the array:
<code cpp>
<lang cpp>
// Create a list of numbers from 1 to the size of the vector.
// Create a list of numbers from 1 to the size of the vector.
size_t size = myVector.size();
size_t size = myVector.size();
for(int i = 0; i < size; ++i)
for(int i = 0; i < size; ++i)
myVector[i] = i + 1;
myVector[i] = i + 1;
</code>
</lang>
'''std::vector''' also provides iterators, allowing you to iterate through a vector's elements the same way you might any other STL container class.
'''std::vector''' also provides iterators, allowing you to iterate through a vector's elements the same way you might any other STL container class.
// Create a list of numbers from 1 to the size of the vector.
// Create a list of numbers from 1 to the size of the vector.
<code cpp>
<lang cpp>
std::vector<int> myVector;
std::vector<int> myVector;
int val = 0;
int val = 0;
Line 94: Line 94:
++it)
++it)
*it = ++val;
*it = ++val;
</code>
</lang>
A vector can also explicitly be resized:
A vector can also explicitly be resized:
<code cpp>
<lang cpp>
std::vector<int> myVector;
std::vector<int> myVector;
myVector.resize(10); // now the vector contains 10 elements, all of which are 0
myVector.resize(10); // now the vector contains 10 elements, all of which are 0
myVector.resize(15, 3); // now the vector contains 15 elements, the 5 new got the value 3
myVector.resize(15, 3); // now the vector contains 15 elements, the 5 new got the value 3
myVector.resize(12); // the last three elements got removed
myVector.resize(12); // the last three elements got removed
</code>
</lang>
Also note that a vector can already be filled at construction time:
Also note that a vector can already be filled at construction time:
<code cpp>
<lang cpp>
std::vector v1(10); // a vector of 10 ints, all initialized with 0
std::vector v1(10); // a vector of 10 ints, all initialized with 0
std::vector v2(5, 7); // a vector containing 5 ints, all inizialized with 7
std::vector v2(5, 7); // a vector containing 5 ints, all inizialized with 7
Line 109: Line 109:
std::vector v3(a, a+10); // a vector containing 10 ints, initialized with the elements of a (i.e. v3[0]==a[0] etc.)
std::vector v3(a, a+10); // a vector containing 10 ints, initialized with the elements of a (i.e. v3[0]==a[0] etc.)
std::vector v4 = v3; // v4 is a copy of v3
std::vector v4 = v3; // v4 is a copy of v3
</code>
</lang>


== {{header|Python}} ==
== {{header|Python}} ==
Line 115: Line 115:
Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:
Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:


<code python>
<lang python>
myArray = [0] * size
myArray = [0] * size
</code>
</lang>


However this will not work as intended if one tries to generalize from the syntax:
However this will not work as intended if one tries to generalize from the syntax:


<code python>
<lang python>
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
</code>
</lang>


This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of mutables (strings, numbers) and immutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of mutables (strings, numbers) and immutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.
Line 129: Line 129:
To initialize a list of lists one could use a pair of nested list comprehensions like so:
To initialize a list of lists one could use a pair of nested list comprehensions like so:


<code python>
<lang python>
myArray = [[0 for x in range(width)] for y in range(height)]
myArray = [[0 for x in range(width)] for y in range(height)]
</code>
</lang>


That is equivalent to:
That is equivalent to:


<code python>
<lang python>
myArray = list()
myArray = list()
for x in range(height):
for x in range(height):
myArray.append([0] * width)
myArray.append([0] * width)
</code>
</lang>

Revision as of 14:02, 31 January 2009

Task
Array Initialization
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate how to initialize an array variable with data.

See Creating_an_Array for this topic.

Ada

The array value obtained directly from data is called array aggregate. Considering these array declarations: <lang ada> type Vector is array (Integer range <>) of Integer; type Matrix is array (Integer range <>, Integer range <>) of Integer; type String is array (Integer range <>) of Character; type Bits is array (Integer range <>) of Boolean; </lang> Initialization by an aggregate using positional and keyed notations: <lang ada> X : Vector := (1, 4, 5); Y : Vector (1..100) := (2|3 => 1, 5..20 => 2, others => 0); E : Matrix := ((1, 0), (0, 1)); Z : Matrix (1..20, 1..30) := (others => (others => 0)); S : String := "ABCD"; L : String (1..80) := (others => ' '); B : Bits := not (1..2 => False); -- Same as (1..2 => True) </lang> Note that the array bounds, when unconstrained as in these examples can be either determined by the aggregate, like the initialization of X shows. Or else they can be specified as a constraint, like for example in the initialization of Y. In this case others choice can be used to specify all unmentioned elements. But in any case, the compiler verifies that all array elements are initialized by the aggregate. Single dimensional arrays of characters can be initialized by character strings, as the variable S shows. Of course, array aggregates can participate in array expressions and these expressions can be used to initialize arrays. The variable B is initialized by an aggregate inversed by the operation not.

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
MODE VEC = FLEX[0]INT; # VECTOR is builtin in ALGOL 68R #
MODE MAT = FLEX[0,0]INT;
# MODE STRING = FLEX[0]CHAR; builtin #
MODE BOOLS = FLEX[0]BOOL; # BITS is builtin in the standard #

Initialization by an aggregate using positional and keyed notations:

VEC x := (1, 4, 5);
[100]INT y; FOR i TO UPB y DO y[i]:=0 OD; FOR i FROM 5 TO 20 DO y[i]:= 2 OD; y[2]:=y[3]:= 1;
MAT e := ((1, 0), (0, 1));
[20,30]INT z; FOR i TO UPB z DO FOR j TO 2 UPB z DO z[i,j]:=0 OD OD;
STRING s := "abcd";
STRING l := " "*80;
[2]BOOL b := (TRUE, TRUE);
SKIP

C++

Simple arrays in C++ have no bounds-checking. In order to safely modify the array's contents, you must know in advance both the number of dimensions in the array and the range for each dimension. In C++, all arrays are zero-indexed, meaning the first element in the array is at index 0.

To assign a single value to an array, one uses the [] operator. <lang cpp> // Assign the value 7 to the first element of myArray. myArray[0] = 7; </lang> If myArray has ten elements, one can use a loop to fill it. <lang cpp> // Assign the sequence 1..10 to myArray for(int i = 0; i < 10; ++i)

 myArray[i] = i + 1;

</lang> If myArray has two dimensions, you can use nested loops. <lang cpp> // Create a multiplication table for(int y = 0; y < 10; ++y)

 for(int x = 0; x < 10; ++x)
   myArray[x][y] = (x+1) * (y+1);

</lang>

STL

Library: STL

STL provides std::vector, which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.

<lang cpp> myVector.push_back(value); </lang> Like simple arrays, std::vector allows the use of the [] operator, and once an element has been added, it can be changed the same way a simple array can. <lang cpp> myVector[0] = value; </lang> Unlike simple arrays, std::vector allows you to determing the size of the array. You can use this set all of the values in the array: <lang cpp> // Create a list of numbers from 1 to the size of the vector. size_t size = myVector.size(); for(int i = 0; i < size; ++i)

 myVector[i] = i + 1;

</lang> std::vector also provides iterators, allowing you to iterate through a vector's elements the same way you might any other STL container class.

 // Create a list of numbers from 1 to the size of the vector.

<lang cpp> std::vector<int> myVector; int val = 0; for(std::vector<int>::iterator it = myVector.begin();

   it != myVector.end();
   ++it)
 *it = ++val;

</lang> A vector can also explicitly be resized: <lang cpp> std::vector<int> myVector; myVector.resize(10); // now the vector contains 10 elements, all of which are 0 myVector.resize(15, 3); // now the vector contains 15 elements, the 5 new got the value 3 myVector.resize(12); // the last three elements got removed </lang> Also note that a vector can already be filled at construction time: <lang cpp> std::vector v1(10); // a vector of 10 ints, all initialized with 0 std::vector v2(5, 7); // a vector containing 5 ints, all inizialized with 7 int a[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; std::vector v3(a, a+10); // a vector containing 10 ints, initialized with the elements of a (i.e. v3[0]==a[0] etc.) std::vector v4 = v3; // v4 is a copy of v3 </lang>

Python

Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:

<lang python> myArray = [0] * size </lang>

However this will not work as intended if one tries to generalize from the syntax:

<lang python> myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!! </lang>

This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of mutables (strings, numbers) and immutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.

To initialize a list of lists one could use a pair of nested list comprehensions like so:

<lang python> myArray = [[0 for x in range(width)] for y in range(height)] </lang>

That is equivalent to:

<lang python> myArray = list() for x in range(height):

  myArray.append([0] * width)

</lang>