I want to create dynamically multidimensional vector. Its dimension depends upon user input. According to user input i created a string which contains the name (e.g. table[2][3][4])
dynamically. Now i want to use this string to access vector variables. But i can not successful, please guide me, i will be thankful to you.
Here is my code.
*****creating matrix of test_var.size() size*******
typedef vector< vector < unsigned int > > contingency_table;
contingency_table table(test_var.size());
for (unsigned int i=0; i < test_var.size(); i++)
{
vector <unsigned int> dim;
table[i]= dim ;
}
********* to access variables ************
static string str= "table";
for ( int j=0; j < 3; j++)
for (int k=0; k< test_var.size(); k++)
{
std::ostringstream table_index;
table_index << "[" << k << "]";
str = str + table_index.str();
cout<<"\n string name is " << str;
}
*****************************************
So, "str" contains the exact vector name along with index (table[2][3][4]).
Now i want to use it to insert and to retrieve value of vector table.
You can't use the string directly. You could indirectly parse out the name and index, then check those, but I don't think that is what you want. You are probably looking for something like std::map:
You can create a matrix with an arbitrary number of dimensions with something like this:
1 2 3 4 5 6
template <typename T>
struct Matrix{
std::vector<Matrix *> dimension; //stores a pointer for each element in the
//current dimension
T data; //Reserved for terminal Matrixes (i.e. when !this->dimension.size())
};
My previous reply is wrong. I didn't quite understand what you wanted to do then.
Now i want to use this string to access vector variables.
The string is useless. If you're taking user input, then you might as well use it to access elements in the vector:
1 2 3
int a,b;
//a and b are filled with user input here.
table[a][b];
If you used your string, you'd have to parse to obtain the values, but since you were the one who created it, it doesn't make sense. It's like digging a hole just so you have a hole to fill.
It would be different if the user entered "table[2][3][4]" and you had to get the element with that