如何使用 std::valarray
来存储/操作二维数组?
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.
我已经知道 Boost.MultiArray、Boost.uBlas 和 Blitz++.
I'm already aware of Boost.MultiArray, Boost.uBlas, and Blitz++.
请随意回答为什么我不应该在我的用例中使用 valarray.但是,我希望多维数组的内存是一个连续的(列 x 行)块.没有 Java 风格的嵌套数组.
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.
我的头顶:
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
提供了许多有趣的方法来访问元素,通过切片、掩码、多维切片或间接表.参见 std::slice_array
、std::gslice_array
、std::mask_array
和 std::indirect_array
更多详情.
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.
这篇关于如何使用 std::valarray 存储/操作连续的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!