Skip to main content

Create multi-dimensional variables, read data file in C++

Answered

Comments

2 comments

  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Hi,

    Regarding your first question. The workforce1_c++.cpp example shows an application of a 2 dimensional variable object. For 3 dimensions, your code might look something like

    #include "gurobi_c++.h"
    #include <sstream>
    using namespace std;

    [...]

    int I = 3;
    int J = 4;
    int K = 5;
    GRBVar*** vars = 0;
    [...]
    vars = new GRBVar**[I];
    for(int i = 0; i < I; i++){
    vars[i] = new GRBVar*[J];
    for(int j = 0; j < J; j++){
    vars[i][j] = model.addVars(K);
    for(int k = 0; k < K; k++){
    ostringstream vname;
    vname << "v[" << i << "," << j << "," << k << "]";
    vars[i][j][k].set(GRB_CharAttr_VType, GRB_BINARY);
    vars[i][j][k].set(GRB_StringAttr_VarName, vname.str());
    }
    }
    }
    for (int i = 0; i < I; i++){
    GRBLinExpr lhs = 0;
    for (int j = 0; j < J; j++){
    for(int k = 0; k < K; k++){
    lhs += vars[i][j][k];
    }
    }
    model.addConstr(lhs == 1);
    }
    [...]

    // Don't forget to delete
    for (int i = 0; i < I; i++){
    for (int j = 0; j < J; j++){
    delete[] vars[i][j];
    }
    delete[] vars[i];
    }
    delete[] vars;

    Regarding your second question. There is a vast number of ways to read in data from a file in C++. One way is described in the stackoverflow post Read file line by line using ifstream in C++.

    Best regards,
    Jaromił

    0
  • Zeyu Wang
    Gurobi-versary
    First Comment
    First Question

    Thank you so much for your help Jaromił! That helps me a lot! 

    Best,

    Zeyu

    0

Please sign in to leave a comment.