How can I use a std::valarray to store/manipulate a 2D array?
I\'d like to see an example of a 2D array with elements accessed by row/column indices. So
#include
#include
using namespace std;
typedef valarray > va2d;
int main()
{
int data[][3] = { {1, 2, 3}, {4, 5, 6} };
va2d mat(valarray(3), 2);
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
mat[ i ][ j ] = data[ i ][ j ];
}
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
cout << mat[ i ][ j ] << endl;
}
More on valarray:
vector like container with special member functions for slicing and dicing.vector access may be fastervalarray: E.g:3 In addition, many member and related functions of valarray can be successfully instantiated and will exhibit well-defined behavior if and only if T satisfies additional requirements specified for each such member or related function.
4 [ Example: It is valid to instantiate valarray, but operator>() will not be successfully instantiated for valarray operands, since complex does not have any ordering operators. —end example ]
Edit#2: The standard gurantees that vector, like arrays, always use contiguous memory. Also, we have:
26.5.2 Class template valarray
1 The class template valarray is a one-dimensional smart array, with elements numbered sequentially from zero. It is a representation of the mathematical concept of an ordered set of values. The illusion of higher dimensionality may be produced by the familiar idiom of computed indices, together with the powerful subsetting capabilities provided by the generalized subscript operators.
and further:
26.5.2.3 valarray element access
4 Likewise, the expression &a[i] != &b[j] evaluates as true for any two arrays a and b and for any size_t i and size_t j such that i is less than the length of a and j is less than the length of b. This property indicates an absence of aliasing and may be used to advantage by optimizing compilers.