构造和操作2d数组的最佳现代c ++方法是什么 [英] what is the best modern c++ approach to construct and manipulate a 2d array
问题描述
就像标题中一样,我找到了很多解决方案.大多数人会说std::array<4, std::array<4, int>>
或std::vector<std::vector<int>>
是好的,但是,我发现它看起来很杂乱,很难扩展到多维数组.另外,我担心这些数组实际上是对象数组,可能会产生一些开销(我想是这样,并不是很确定).那么最好的方法是什么?
As in the title, I got to find tons of solutions doing this. Most people would say std::array<4, std::array<4, int>>
or std::vector<std::vector<int>>
are good, which, however, I find looks teidous and hard to extend to multi-dimensional arrays. Also, I fear that these arrays are actually object-arrays which is likely to be with some overhead (I guess so, not really certain). So what is the best way to do this ?
推荐答案
我碰巧发现了这个未经测试的示例.如果可行,那么很好,否则它是如何在1D
数组上创建2D
视图的一个示例:
I happen to have this completely untested example lying around. If it works, good, otherwise it is an example of how you might go about creating a 2D
view onto a 1D
array:
template<typename T>
class two_dee_array
{
public:
two_dee_array(std::size_t row, std::size_t col)
: v(row * col), stride(col) {}
T& operator()(std::size_t row, std::size_t col)
{ return v[(row * stride) + col]; }
T const& operator()(std::size_t row, std::size_t col) const
{ return v[(row * stride) + col]; }
std::size_t col_size() const { return stride; }
std::size_t row_size() const { return v.size() / stride; }
auto begin() { return std::begin(v); }
auto end() { return std::end(v); }
auto begin() const { return std::begin(v); }
auto end() const { return std::end(v); }
auto cbegin() const { return std::cbegin(v); }
auto cend() const { return std::cend(v); }
private:
std::vector<T> v;
std::size_t stride;
};
这篇关于构造和操作2d数组的最佳现代c ++方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!