对于这个数组:
vector<vector<int> > v;
v.push_back(vector<int>(0));
v.back().push_back(1);
v.back().push_back(2);
v.back().push_back(3);
v.back().push_back(4);
我可以很容易地输出 {1, 2, 3, 4}:
cout << v[0][0] << endl;
cout << v[0][1] << endl;
cout << v[0][2] << endl;
cout << v[0][3] << endl;
要将其作为平面数组访问,我可以这样做:
int* z = (int*)&v[0].front();
cout << z[0] << endl;
cout << z[1] << endl;
cout << z[2] << endl;
cout << z[3] << endl;
现在,如何将多维 vector 作为平面多维数组访问?我无法使用与访问一维 vector 相同的格式:
// This does not work (outputs garbage)
int** n = (int**)&v.front();
cout << n[0][0] << endl;
cout << n[0][1] << endl;
cout << n[0][2] << endl;
cout << n[0][3] << endl;
我发现的解决方法是这样做:
int** n = new int* [v.size()];
for (size_t i = 0; i < v.size(); i++) {
n[i] = &v.at(i).front();
}
cout << n[0][0] << endl;
cout << n[0][1] << endl;
cout << n[0][2] << endl;
cout << n[0][3] << endl;
是否有一种方法可以像平面 c 样式数组一样访问整个多维 vector ,而无需在访问数据之前动态分配数据上方的每个维度?
速度在实现中并不重要,维护的清晰度才是最重要的。多维 vector 非常适合存储数据。但是,我还想在 SDK 中将数据公开为平面 c 样式数组,以便其他语言可以轻松访问它。这意味着将 vector 公开为 STL 对象是不行的。
我想出的解决方案可以很好地满足我的需求,因为我只在处理的最后评估一次数组以“展平”它。然而,有没有更好的方法来解决这个问题呢?或者我是否已经以最好的方式做到了这一点,而无需重新实现我自己的数据结构(因为我的扁平化代码只有几行,所以太过分了)。
谢谢 friend 们的建议!
最佳答案
vector
的缓冲区通常是动态分配的。
这意味着当您有一个由 vector
组成的 vector
时,那么对于内部缓冲区,您将拥有类似于指针数组的东西,每个指针都指向一个数组.
如果您需要在相同数据的 1D 和 2D View 之间切换,最简单的可能就是定义一个 2D 数组类,如下所示(即兴):
typedef ptrdiff_t Size;
typedef Size Index;
template< class Item >
class Array2D
{
private:
std::vector< Item > items_;
Size width_;
Size height_;
Index indexFor( Index const x, Index const y )
{ return y*width_ + x; }
public:
Size width() const { return width_; }
Size height() const { return height_; }
Item& operator()( Index const x, Index const y )
{ return items_[indexFor( x, y )]; }
Item const& operator()( Index const x, Index const y ) const
{ return items_[indexFor( x, y )]M; }
Size bufferSize() const { return width_*height_; }
Item* buffer() { return &items_[0]; }
Item const* buffer() const { return &items_[0]; }
Array2D( Size const w, Size const h )
: items_( w*h )
, width_( w )
, height_( h )
{}
};
然后你可以做类似的事情
Array2D< int > a( 4, 3 );
for( Index y = 0; y < a.height(); ++y )
{
for( Index x = 0; x < a.width(); ++x )
{
foo( a( x, y ) );
}
}
和
Array2D< int > a( 4, 3 );
int* const pb = a.buffer();
for( Index i = 0; i < a.bufferSize(); ++i )
{
foo( pb[i];
}
关于c++ - 将 vector <vector<int>>作为平面数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993403/