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;

  for (auto& c : leg){ 
    std::cout << c->date() << " , " << c->amount()  << std::endl;
  return 0;

1 Answer 1


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.

  • $\begingroup$ Thanks Luigi, it worked perfectly! $\endgroup$
    – mele
    Commented Apr 18, 2021 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.