TRIQS/nda 1.3.0
Multi-dimensional array library for C++
|
In this example, we show how to initialize arrays and assign to them in different ways.
All the following code snippets are part of the same main
function:
The simplest way to initialize an array is to assign a scalar to it:
Output:
Note that the behavior of the assignment depends on the algebra of the array.
While the scalar is assigned to all elements of an array, for matrices it is only assigned to the elements on the shorter diagonal:
Output:
The scalar type can also be more complex, e.g. another nda::array:
Output:
The copy and move assignment operations behave as expected:
Output:
Note: Be careful when reusing an object after it has been moved (see the note at Copy/Move constructors)!
To assign an object that satisfies the nda::Array concept to an array is similar to Constructing an array from an nda::Array.
Output:
Many assignment operations resize the left hand side array if necessary.
In the above example, the first assignment does not need to do a resize because the left hand side array already has the correct shape.
This is not true for the second assignment. A2
has been default constructed and therefore has a size of 0.
It is possible to assign an object that satisfies the std::ranges::contiguous_range
concept to an 1-dimensional array:
Output:
As expected, the elements of the range are simply copied into the array.
We can also initialize an array by assigning to each element manually. This can be done in different ways.
For example,
using traditional for-loops:
Output:
using a range-based for-loop:
Output:
using nda::for_each:
Output:
While the traditional for-loops are perhaps the most flexible option, it becomes tedious quite fast with increasing dimensionality.
This has already been explained in Initializing with CLEF's automatic assignment.
Let us give another example:
Output:
The advantage of CLEF's automatic assignment becomes obvious when we rewrite line 3 from above using traditional for-loops: