Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c++ - How can I use a std::valarray to store/manipulate a contiguous 2D array?

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.

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

Feel free to answer why I shouldn't use valarray for my use case. However, I want the memory for the multidimensional array to be a contiguous (columns x rows) block. No Java-style nested arrays.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Off the top of my head:

template <class element_type>
class matrix
{
public:
    matrix(size_t width, size_t height): m_stride(width), m_height(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...