4 ms·
Yep, in C++ you can pass in a lambda to create the comparator inline: std::sort( myvec.begin(), myvec.end(), [](obj& A, obj& b) { return
by throwaway080383 9y ago
Yep, in C++ you can pass in a lambda to create the comparator inline:
std::sort(
myvec.begin(),
myvec.end(),
[](obj& A, obj& b) {
return A.attr < B.attr;
}
);
- brianwawok 9y agoThat is disgusting as a non-C++ programmer
- mhh__ 9y agoeh, it's not Haskell (or even D for that matter) but C++ has come a long way in the last few years.
- electricslpnsld 9y agoIf you use std::begin and std::end instead of the member functions this will even work with old-school C-style arrays.
- emmelaich 9y agoYes, and you can even use the range syntax instead of begin/end. Here's a file with a few different ways https://gist.github.com/anonymous/78b4f257e60d55537b36e2e4f3c6de9d https://gist.github.com/anonymous/78b4f257e60d55537b36e2e4f3...
- emmelaich 9y ago.. and Herb Sutter recommends those free functions over the member functions for this reason -- genericity.
- nrdvana 9y agoWhat I'm talking about is arbitrary attributes that might not exist on the base class, resulting in something like: std::sort( myvec.begin(), myvec.end(), [](obj& A, obj& b) { int A_attr1= dynamic_cast<Thing1*>(&A)? dynamic_cast<Thing1*>(&A)->attr1 : dynamic_cast<Thing2*>(&A)? dynamic_cast<Thing2*>(&A)->attr1 : -1; int B_attr1= dynamic_cast<Thing1*>(&B)? dynamic_cast<Thing1*>(&B)->attr1 : dynamic_cast<Thing2*>(&B)? dynamic_cast<Thing2*>(&B)->attr1 : -1; return A_attr1 < B_attr1; } ); and then compare that to @list= sort { ($a->{attr1} // -1) <=> ($b->{attr1} // -1) } @list;