One simple solution is to use vectors. Consider this simple example:
#include <iostream> #include <vector> void f (std::vector<std::vector<int> > &v) { for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) v[i][j] = i * 3 + j; } int main() { std::vector<std::vector<int> > v (3, std::vector<int> (3, 0)); f (v); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) std::cout << v[i][j] << ' '; }
In main, a 2D vector of ints (3x3) is created. The constructor shows 3 elements, all initialized with a vector of ints, which are in turn created with 3 elements initialized to 0.
Then, the vector is passed by reference to the function f, which assigns increasing values. When the vector is printed in main, it shows:
0 1 2 3 4 5 6 7 8
As you can see, their use is very similar to normal arrays, but they are actually contained, and provide easy access to a new level of programming using the STL.
In C++11, their use becomes even more familiar. You can assign vectors as follows:
std::vector<int> v0 = {2, 5}; std::vector<std::vector<int> > v1 { {1,2,3} , {4,5,6} , {7,8,9} };
Note that for vectors of multiple dimensions it's a good idea to encapsulate it in a matrix class of some sort with an underlying 1D vector type instead.
Edit:
Here's an example of initializing a 1D and 2D vector to specified elements. As seen above, this is easy in C++11, but if you have an array already, it's still pretty quick.
int a [5] = {1,2,3,4,5}; //normal std::vector<int> v1 (a, a +5); //create using beginning and ending addresses of a int b[3][3] = { {1,2,3} , {4,5,6} , {7,8,9} }; //normal std::vector<std::vector<int> > v2; //empty vector for (int i = 0; i < 3; ++i) //3 in first dimension v2.push_back (std::vector<int> (b [i], b [i] + 3)); //push a vector with the appropriate 3 elements of b onto the back of v2
For going through one element at a time, you can do this:
std::vector<std::vector<int> > v (3, std::vector<int> (3)); for (int i = 0; i < v.size(); ++i) //v.size() == 3 for (int j = 0; j < v [i].size(); ++j) adjustElement (v [i][j]); //replace with what you need
std::vector:vector<int> &tableValueswould be your parameter.