Solving your first model in C++¶
LocalSolver is implemented in C++ language. A highly-portable C++ library is provided with object-oriented application programming interfaces (APIs), allowing a full integration of LocalSolver in your business applications. LocalSolver’s APIs are lightweight, with only a few classes to manipulate. Remind that LocalSolver is a black-box math programming solver: having instantiated the model, no additional code has to be written in order to run the solver.
A small example¶
Below is given the C++ code for solving the knapsack toy instance introduced
during the Quick tour of LocalSolver’s modeler.
The corresponding source file can be retrieved in examples/toy
.
//********* toy.cpp *********
#include <iostream>
#include "localsolver.h"
using namespace localsolver;
using namespace std;
int main()
{
try {
lsint weights[] = {10, 60, 30, 40, 30, 20, 20, 2};
lsint values[] = {1, 10, 15, 40, 60, 90, 100, 15};
lsint knapsackBound = 102;
// Declares the optimization model.
LocalSolver localsolver;
LSModel model = localsolver.getModel();
// 0-1 decisions
LSExpression x[8];
for (int i = 0; i < 8; i++)
x[i] = model.boolVar();
// knapsackWeight <- 10*x0 + 60*x1 + 30*x2 + 40*x3 + 30*x4 + 20*x5 + 20*x6 + 2*x7;
LSExpression knapsackWeight = model.sum();
for (int i = 0; i < 8; i++)
knapsackWeight += weights[i]*x[i];
// knapsackWeight <= knapsackBound;
model.constraint(knapsackWeight <= knapsackBound);
// knapsackValue <- 1*x0 + 10*x1 + 15*x2 + 40*x3 + 60*x4 + 90*x5 + 100*x6 + 15*x7;
LSExpression knapsackValue = model.sum();
for (int i = 0; i < 8; i++)
knapsackValue += values[i]*x[i];
// maximize knapsackValue;
model.maximize(knapsackValue);
// close model, then solve
model.close();
// Parameterizes the solver.
localsolver.getParam().setTimeLimit(1);
localsolver.solve();
} catch (const exception& e) {
cerr << "Error occurred:" << e.what() << endl;
return 1;
}
return 0;
}
You can observe that the structure of the C++ program follows the structure of corresponding LSP. First, we read input data. Then, we declare the knapsack model by creating some expressions. Once the model is closed, we can parameterize the search before launching the solver.
Compiling and running the C++ program¶
On Windows, the above program is compiled and launched using the following lines in Visual Studio Command Prompt (x86 or x64, depending on your version of LocalSolver):
cl /EHsc toy.cpp -I%LS_HOME%\include /link %LS_HOME%\bin\localsolver.dll.lib
toy
On Linux or Mac OS, the same program is compiled and launched using the following lines:
g++ toy.cpp -I/opt/localsolver_4_5/include -llocalsolver -lpthread -o toy
./toy
If you have some troubles in compiling or launching the program, please have a look to the Installation & licensing. We invite users willing to go further with APIs to consult the C++ API Reference.