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.

Quadratic AI

Quadratic AI โ€“ The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo ๐Ÿ“Šโœจ

Top comments (0)

Image of PulumiUP 2025

From Cloud to Platforms: What Top Engineers Are Doing Differently

Hear insights from industry leaders about the current state and future of cloud and IaC, platform engineering, and security.

Save Your Spot

๐Ÿ‘‹ Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someoneโ€™s dayโ€”drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay