@@ -76,14 +76,17 @@ void CommoditySwap::build(const QuantLib::ext::shared_ptr<EngineFactory>& engine
7676 // the map entry gets overwritten and the fixed leg with empty tag matches a random floating leg with empty tag.
7777 // This is by design i.e. use tags if you want to link specific legs.
7878 map<string, Leg> floatingLegs;
79- for (const auto & legDatum : legData_) {
79+ vector<Size> legsIdx;
80+ for (Size t = 0 ; t < legData_.size (); t++) {
81+ const auto & legDatum = legData_.at (t);
8082
8183 const string& type = legDatum.legType ();
8284 if (type == " CommodityFixed" )
8385 continue ;
8486
8587 // Build the leg and add it to legs_
8688 buildLeg (engineFactory, legDatum, configuration);
89+ legsIdx.push_back (t);
8790
8891 // Only add to map if CommodityFloatingLegData
8992 if (auto cfld = QuantLib::ext::dynamic_pointer_cast<CommodityFloatingLegData>(legDatum.concreteLegData ())) {
@@ -92,7 +95,8 @@ void CommoditySwap::build(const QuantLib::ext::shared_ptr<EngineFactory>& engine
9295 }
9396
9497 // Build any fixed legs skipped above.
95- for (const auto & legDatum : legData_) {
98+ for (Size t = 0 ; t < legData_.size (); t++) {
99+ const auto & legDatum = legData_.at (t);
96100
97101 // take a copy, since we might modify the leg datum below
98102 auto effLegDatum = legDatum;
@@ -144,8 +148,21 @@ void CommoditySwap::build(const QuantLib::ext::shared_ptr<EngineFactory>& engine
144148
145149 // Build the leg and add it to legs_
146150 buildLeg (engineFactory, effLegDatum, configuration);
151+ legsIdx.push_back (t);
147152 }
148153
154+ // Reposition the leg-based data to match the original order according to legData_
155+ vector<Leg> legsTmp;
156+ vector<bool > legPayersTmp;
157+ vector<string> legCurrenciesTmp;
158+ for (const Size idx : legsIdx) {
159+ legsTmp.push_back (legs_.at (idx));
160+ legPayersTmp.push_back (legPayers_.at (idx));
161+ legCurrenciesTmp.push_back (legCurrencies_.at (idx));
162+ }
163+ legs_ = legsTmp;
164+ legPayers_ = legPayersTmp;
165+ legCurrencies_ = legCurrenciesTmp;
149166
150167 // Create the QuantLib swap instrument and assign pricing engine
151168 auto swap = QuantLib::ext::make_shared<QuantLib::Swap>(legs_, legPayers_);
0 commit comments