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

后端 未结 4 1526
天命终不由人
天命终不由人 2020-12-03 02:10

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 02:52

    Off the top of my head:

    template 
    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 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.

提交回复
热议问题