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;
}
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;
}
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.
Top comments (0)