Accessing a vector<vector<int>> as a flat array

Posted by user1762276 on Stack Overflow See other posts from Stack Overflow or by user1762276
Published on 2012-10-20T22:53:42Z Indexed on 2012/10/20 23:00 UTC
Read the original article Hit count: 226

Filed under:
|
|
|
|

For this array:

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);

I can output {1, 2, 3, 4} easily enough:

cout << v[0][0] << endl;
cout << v[0][1] << endl;
cout << v[0][2] << endl;
cout << v[0][3] << endl;

To access it as a flat array I can do this:

int* z = (int*)&v[0].front();

cout << z[0] << endl;
cout << z[1] << endl;
cout << z[2] << endl;
cout << z[3] << endl;

Now, how do I access the multidimensional vector as a flat multidimensional array? I cannot use the same format as accessing a single-dimensional 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;

The workaround I've found is to do this:

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;

Is there a way to access the entire multidimensional vector like a flat c-style array without having to dynamically allocate each dimension above the data before accessing it?

Speed is not critical in the implementation and clarity for maintenance is paramount. A multidimensional vector is just fine for storing the data. However, I want to also expose the data as a flat c-style array in the SDK so that it can be easily accessible by other languages. This means that exposing the vectors as an STL object is a no go.

The solution I came up with works fine for my needs as I only evaluate the array once at the very end of processing to "flatten" it. However, is there a better way to go about this? Or am I already doing it the best way I possibly can without re-implementing my own data structure (overkill since my flatten code is only a few lines).

Thank you for your advice, friends!

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl