简体   繁体   中英

Declaring multidimensional vector with variable number of dimensions in C++

I am trying to declare a multidimensional vector with variable number of dimensions (user input).

here is what I have:

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

vector< double > data;

int main() {
    int numberDimensions = 4;
    for (int it = 0; it < numberDimensions; it++){
      // Nor sure what to put here
    }
    return 0;
}

Another solution is by using an if statement at the begining but I was wondering if another solution exists ?

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int main() {
    int numberDimensions = 4; 
    if (numberDimensions==0)
        cout << 'error' << endl;
    else if (numberDimensions==1)
         vector< double> data;
    else if (numberDimensions==2)
         vector< vector< double> > data;
    else if (numberDimensions==3)
         vector< vector< vector< double> > > data;
    else if (numberDimensions==4)
         vector< vector< vector< vector< double> > > > data;
    return 0;
}

Thanks for any suggestions,

As suggested in the comments here is the solution I followed:

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

vector< double > data;

int main() {

    std::vector<int> parameter1 {34,23,58};
    std::vector<int> parameter2 {1,2,3};

    data = vector< double > (parameter1.size()*parameter2.size());
    calculateResult(data);

   // If I want to access the result for Parameter1 = 58 and Parameter = 2 I do:
    int index1 = 2
    int index2 = 1
    double selectedResult = data[index1*parameter1.size()+index2];

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM