DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, Pass function to algorithm vs Lambda expression

If we need to use standard functions with custom objects (our defined struct or class) before C++11, we can only pass functions to algorithms.

struct City {
    string name;
    double population;
};
// compare City by population
bool cmpfnc(const City& a, const City& b) {
    return a.population < b.population;
}
// then we can use it
vector<City> vCity = { {"city 1", 140000}, {"city 2", 100000},{"city 3", 700000},{"city 4", 500000} };
sort(vCity.begin(), vCity.end(), cmpfnc); //pass cmpfnc function  to standard stl sort
for (auto c : vCity) {
     cout << "City name: " << c.name << " population: " << c.population << endl;
}
Enter fullscreen mode Exit fullscreen mode

from C++11, Lambda expression makes it simple

vector<City> vCity = { {"city 1", 140000}, {"city 2", 100000},{"city 3", 700000},{"city 4", 500000} };
//lambda expression
sort(vCity.begin(), vCity.end(), [](const City& a, const City& b) {return a.population < b.population; });
for (auto c : vCity) {
   cout << "City name: " << c.name << " population: " << c.population << endl;
}
Enter fullscreen mode Exit fullscreen mode

But sometimes, I also forget the ";" in the code of a lambda expression [](const City& a, const City& b) {return a.population < b.population;} so don't forget it.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more