I have a scenario that looks like this:
#include <algorithm>
using namespace std;
// a "heavy" struct with lots of members
struct B {
int key;
// other members
}
class A {
vector<B> bs;
}
I want to sort the bs by their keys. Now, a way I’ve done this in the past to avoid swapping Bs (since they’re rather heavy), is to define a vector of indices and sort the indices instead. This works if bs is not a class member.
e.g.
vector<B> bs;
vector<size_t> indices;
bool pred(size_t i, size_t j) { return bs[i] < bs[j]; }
indices.resize(bs.size());
for (size_t i = 0; i < bs.size(); i++) indices[i] = i;
std::sort(indices.begin(), indices.end(), pred);
However, when bs is a class member, this “technique” fails because the predicate can only take two parameters. In particular, there’s no way of passing “this”.
I can see three different ways to solve this problem:
- Don’t bother with the indices. Just overload operator
<to handle instances of B. This whole indices thing is just premature optimization 🙂 - Have a global pointer to
bs, set it before callingsort, and use it inpred. - Use closures. This would be pretty cool, except I’m not using C++11.
Is there any other way of doing this? Thanks!
Assuming that
bis inclass Aand is accessible through a member function calledget, you can write a functor like this:And use it like this: