Number of entries in IloExpr

Viewed 58

I'm creating a CPLEX LP (C++) and am creating constraints using IloExpr in the usual way. eg.

IloExpr cons(m_env);

for (auto& pID : values) {

    if (pID != -1) {
        cons += variables[pID];
    }
}

m_model.add(IloRange(m_env, 0.0, cons, 1.0));

At the end of the loop, cons may not have any variables if all values are -1. I'd like to check this to avoid adding an empty constraint to the model.

How can I do this?

Thanks.

1 Answers

this is not really a CPLEX issue but you could use a binary variable to remember whether you have added a non empty variable:

IloExpr cons(m_env);

int empty=1;

for (auto& pID : values) {

    if (pID != -1) {
        cons += variables[pID];
        empty=0;
    }
}

if (empty==0) m_model.add(IloRange(m_env, 0.0, cons, 1.0));
Related