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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay