views:

289

answers:

3

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. Something like this pseudo code:

matrix(i,j) = 42;

An example of how to initialize such an array would also be nice.

N.B.: I'm already aware of Boost.MultiArray, Boost.uBlas, and Blitz++.

EDIT:

Feel free to answer why I shouldn't use valarray for my use case.

EDIT2:

I want the memory for the multidimensional array to be a contiguous (columns x rows) block. No Java-style nested arrays.

+1  A: 

Here's an example that includes a bit of matrix manipulation

Liz Albin
Could you at least include a short example that addresses the question? External sites might be down at some point.
Georg Fritzsche
I dont seem to be able to find a 2D `valarray` part in that example but a 2D matrix flattened out. I think the OP wants a `valarray< valarray <T> >` thingy.
dirkgently
@dirkgently: I want the array memory to be contiguous, so no valarray< valarray <T> >. Edited question.
Emile Cormier
+1  A: 

HTH:

#include <iostream>
#include <valarray>

using namespace std;

typedef valarray<valarray<int> > va2d;

int main()
{
    int data[][3] = { {1, 2, 3}, {4, 5, 6} };
    va2d mat(valarray<int>(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;
}

Edit: More on valarray:

  • It is optimized for numeric computation.
  • It is a vector like container with special member functions for slicing and dicing.
  • No iterators
  • Designed for vector machines and perform poorly on current ones: vector access may be faster
  • Was not supported by all compilers (check the documentation) / poorly implemented
  • See 26.1 for the types that can be used as a parameter to valarray<T>: 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.

dirkgently
Oops. Sorry. Didn't clarify my question fast enough. +1 anyways.
Emile Cormier
`valarray` is intended to contain multidimensional arrays without nesting. `valarray<valarray<...> >` should only be necessary for an array of matrices/arrays of different sizes.
Potatoswatter
Wow, thanks for the standard quotes! :-)
Emile Cormier
dirkgently answered before I clarified that I wanted contiguous memory. No need to downvote.
Emile Cormier
From the quotes you posted, it's not clear to me if the valarray data is guaranteed to be contiguous. Can you elaborate?
Emile Cormier
@Emille: Yes they are.
dirkgently
+2  A: 

Off the top of my head:

template <class element_type>
class matrix
{
public:
    matrix(size_t width, size_t height): m_stride(width), m_stride(height), m_storage(width*height) {  }

    element_type &operator()(size_t row, size_t column)
    {
        // column major
        return m_storage[std::slice(column, m_height, m_stride)][row];

        // row major
        return m_storage[std::slice(row, m_stride, m_height)][column];
    }

private:
    std::valarray<element_type> m_storage;
    size_t m_stride;
    size_t m_height;
};

std::valarray provides many interesting ways to access elements, via slices, masks, multidimentional slices, or an indirection table. See std::slice_array, std::gslice_array, std::mask_array, and std::indirect_array for more details.

MSN
Ah yes, thank you. That's what I was looking for. I especially like that you showed both row/column major access.
Emile Cormier
Is the valarray data guaranteed to be contiguous, like vector?
Emile Cormier
From MSDN: The template class describes an object that controls a sequence of elements of type Type that are stored as an array, designed for performing high-speed mathematical operations, and optimized for computational performance. So, I would assume so.
MSN
P.S., feel free to accept this as the answer :)
MSN