Sorry, Im so dumb for not understanding it right away, is a vector of vector of data where data can be any class or STL container or any native data type such as int, double, etc....
Remember that a two dimentional vector is simply a vector of vectors. Each "subvector" or "row" is completely independant from the others, meaning that they can have different size. You can dynamically add elements to change the size of each row, and add elements to the main vector to add more rows.
You can simply use nested loops to build the structure. This is one way to do it:
1 2 3 4 5 6 7 8 9
vector< vector<int> > vec;
for (int i = 0; i < 10; i++) {
vector<int> row; // Create an empty row
for (int j = 0; j < 20; j++) {
row.push_back(i * j); // Add an element (column) to the row
}
vec.push_back(row); // Add the row to the main vector
}
It's not the only way, you may also add empty rows in one loop, and then use another loop that adds columns by inserting an element to all rows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
vector< vector<int> > vec;
for (int i = 0; i < 10; i++) {
vec.push_back(vector<int>()); // Add an empty row
}
for (int j = 0; j < 20; j++) {
for (int i = 0; i < vec.size(); i++) {
vec[i].push_back(i * j); // Add column to all rows
}
// You could also use iterators:
for (vector< vector<int> >::iterator it = vec.begin(); it != vec.end(); ++it) {
it->push_back(j); // Add column to all rows
}
}
There is also another possible way to use a vector as a two dimentional array. If each row will always have the same fixed length, you can use a single vector, and simulate two dimentions by calculating the index from a row and column number:
The last idea is great if you're not going to be changing the matrix a lot, but if you're not going to be changing it, why bother using vectors at all?
Taking the 'simulate-a-2D-array-with-one-dimension' approach runs into trouble when you want to add a new column. Suddenly there's a lot of value-shifting that have to take place. Adding rows isn't bad at all. You could never use .push_back - it would always have to be a .resize() and then adding all the elements, etc. etc.
But, heck, if you just want to build this matrix and then leave the size alone, that's a great idea.