Iterating through OPL elements
Shows how to iterate through the elements of your model.
The OPL Interface libraries enable your applications to iterate
through OPL elements such as arrays (maps) and sets. This feature
is illustrated by the iterators example, which contains
two samples. The iterators example is available in
C++, Java, and .NET Visual Basic and C# at the following locations:
<Install_dir>\opl\examples\opl_interfaces\cpp\src\iterators.cpp
<Install_dir>\opl\examples\opl_interfaces\java\iterators\src\iterators\Iterators.java
<Install_dir>\opl\examples\dotnet\x64_windows_msvc14\VisualBasic\Iterators\Iterators.vb
<Install_dir>\opl\examples\dotnet\x64_windows_msvc14\CSharp\Iterators\Iterators.cs
where <Install_dir> is your installation directory.
Sample1
The
purpose of Sample1 is to check the result of filtering
by iterating on the generated data element. The data element is an
array of strings that is indexed by a set of strings. It is filled
as the result of an iteration on a set of tuples by filtering out
the duplicates. It is based on the transp2.mod model.
The simplified model is:
{string} Products = ...;
tuple Route { string p; string o; string d; }
{Route} Routes = ...;
{string} orig[p in Products] = { o | <p,o,d> in Routes };
Sample2
The
purpose of Sample2 is to output a multidimensional
array x[i][j] to illustrate how arrays and sub-arrays
are managed, as shown in the following code extract.
Output of a multidimensional array
IloIntMap x = opl.getElement("x").asIntMap();
IloSymbolSet s1 = opl.getElement("s1").asSymbolSet();
IloSymbolSet s2 = opl.getElement("s2").asSymbolSet();
// Iterate on the first indexer.
for (IloSymbolSetIterator it1(s1); it1.ok(); ++it1){
// Get the second dimension array from the first dimension.
IloIntMap sub = x.getSub(*it1);
// Iterate on the second indexer of x (that is the indexer of the subarray).
for (IloSymbolSetIterator it2(s2); it2.ok(); ++it2){
// This is the last dimension of the array, so you can directly use the get method.
cout << *it1 << " " << *it2 << " " << sub.get(*it2) << "\n";
}
}
To access the elements of an array, you must first access the sub-arrays until the last dimension, then you can get the values. Here, as there are two dimensions, you have to get one sub-array from which you can directly get the values. The array of integers is indexed by two sets of strings.
The simplified model is:
{string} s1 = ...;
{string} s2 = ...;
{int} x[s1][s2] = ...;
Sample 3
The purpose of sample3 is to output an array of tuples arrayT[i], to illustrate how tuple elements can be accessed.
The simplified model is:
tuple t
{
int a;
int b;
}
{string} ids={"id1","id2","id3"};
t arrayT[ids]=[<1,2>,<2,3>,<1,3>];