Sorting QuantLib Cash Flows by Payment Date
Summary
The document shows how to order a QuantLib leg of cash flows by their dates in C++. A default call to the standard sorting algorithm cannot infer the desired ordering from cash-flow pointers, so the comparison must explicitly use each object’s date.
The suggested approach supplies a comparator lambda to the sorting function and compares the dates of two cash flows. With C++14, generic lambda parameters can make the comparator shorter. The method applies to cash-flow types generally, rather than only simple cash flows. The example explains date ordering in a software library, but offers no discussion of valuation, trading strategy, or market evidence.
Key ideas
- Sort cash flows by providing a comparator that compares their dates.
- A lambda can access the date through each cash-flow pointer.
- C++14 generic lambda parameters can simplify the comparator.
- The same date-based approach applies to different cash-flow types.
Tags
Full text
# Sorting SimpleCashFlows in QuantLib
# Sorting SimpleCashFlows in QuantLib
I would like to sort SimpleCashFlow(s) according to date. I am having trouble incorporing the the less than function < in std::sort
```
#include <iostream>
#include <algorithm>
#include <ql/time/date.hpp>
#include <ql/time/period.hpp>
#include <ql/cashflows/simplecashflow.hpp>
using namespace QuantLib;
int main()
{
Date date(1, January, 2021);
Date date2(1, January, 2020);
Real amount = 100.0;
ext::shared_ptr<SimpleCashFlow> cf1(new SimpleCashFlow(amount,date));
ext::shared_ptr<SimpleCashFlow> cf2(new SimpleCashFlow(amount,date2));
Leg leg;
leg.push_back(cf1);
leg.push_back(cf2);
std::sort(leg.begin(),leg.end());
for (auto& c : leg){
std::cout << c->date() << " , " << c->amount() << std::endl;
}
return 0;
}
```
## Answer by Luigi Ballabio (score 4)
https://quant.stackexchange.com/a/63447
Using a lambda, you can write something like
```
std::sort(leg.begin(), leg.end(),
[](const ext::shared_ptr<CashFlow>& c1,
const ext::shared_ptr<CashFlow>& c2){ return c1->date() < c2->date() });
```
If you can use C++14, the above can be simplified to
```
std::sort(leg.begin(), leg.end(),
[](auto c1, auto c2){ return c1->date() < c2->date() });
```
This works for all cashflow types, not just `SimpleCashFlow`.Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.