loxol loxol - 28 days ago 6
C++ Question

Name an array depening on what is passed to it in a function

How would I go about naming an array depending on what is passed to it. So far I have:

void FileIO::createMatrix(int rows, int cols)
{
name = new double*[rows];
for (int i = 0; i < rows; i++)
{
name[i] = new double[cols];
}
}


How can I go about replacing
name
with an actual name? so I can create many arrays by easily calling this method?

So, instead of creating an array called
name
I could create one called
foo
?

Answer

First, please try not to use dynamic array directly until you are doing something so low-level.. the standard library full of lovely containers. Try to get the best utilization of them.


If my guess is right, you have something like:

class FileIO{
.....
    double** MatrixA;
    double** MatrixB;
    double** MatrixC;
}
void FileIO::createMatrix(int rows, int cols){
    name = new double*[rows];
    for (int i = 0; i < rows; i++){
        name[i] = new double[cols];
    }
}

You can solve your problem by something called pointer to member variable type:

class FileIO{
public:
    double** MatrixA;
    double** MatrixB;
    double** MatrixC;
    void createMatrix(int rows, int cols, double** FileIO::* member_varaible){
        this->*member_varaible= new double*[rows];
        for (int i = 0; i < rows; i++){
            (this->*member_varaible)[i] = new double[cols];
        }
    }
};
int main(){
    FileIO fio;
    fio.createMatrix(5,5,&FileIO::MatrixA);
    fio.createMatrix(2,4,&FileIO::MatrixB);
    fio.createMatrix(4,3,&FileIO::MatrixC);
}

If this was the case, I think you have a bad design and you may need to think about changing it.


Alternative and more realistic solution:

namespace my_utility{
    template <typename T>
    T** create_2d_dynamic_array(int rows, int cols){
        T** temp = new T*[rows];
        for (size_t i = 0; i < rows; i++){
            temp[i] = new T[cols];
        }
        return result;
    }
}

int main(){
   auto foo = my_utility::create_2d_dynamic_array<double>(5,5);
}
Comments