MushinZero MushinZero - 1 month ago 10
C++ Question

Comparing two object variables using sort() within a vector

I have been banging my head against this and google for a while now so I hope it is alright to ask. I am still learning C++ and enjoying it but I don't full understand everything yet and am really just now digging into pointers and classes in my Data Structures class. Why can I not compare the fitness variables of the tree objects using this sort?

I am getting the error: 'Environment::compare': non-standard syntax; use '&' to create a pointer to member.

void Environment::evolve(const int popsize,const int maxgen) {
std::cout << "> evolving function" << std::endl;

std::vector<Tree> popvec;

// Generate initial pop trees and store in array
for (int i = 0; i <= popsize - 1; i++) {
std::cout << "> generating initial population" << std::endl;

Tree membertree;
popvec.push_back(membertree);
}

// Loop for generations
for (int j = 1; j <= maxgen; j++) {
std::cout << "Generation " << j << ":" << std::endl;

// sort array by fitness
std::sort(popvec.begin(), popvec.end(), compare);

// cull herd

// reproduce

}
}

bool Environment::compare(Tree obj1, Tree obj2) {
return (obj1.fitness < obj2.fitness);
}


Thank you for your help.

Edit with header:

#include "Tree.h"

class Environment {
public:
Environment();
~Environment();
void evolve(const int popsize,const int maxgen);
bool compare(Tree obj1, Tree obj2);

private:
Tree* poparray;
};

Answer

The immediate cause of compile error

std::sort(popvec.begin(), popvec.end(), compare);

You're referencing compare, which is a class member function. To pass a pointer to class member (data or function) you need to use the &Class::Member syntax:

std::sort(popvec.begin(), popvec.end(), &Environment::compare);

But this won't work unless compare is a static function - as it should be (or you can do gymnastics with passing a stateful lambda/functor, but there's no reason a sane person would do this).

The real problem

You should change declaration of compare - make it a static member function:

static bool compare(Tree obj1, Tree obj2);

If you do this, changing the sort call syntax is no longer necessary (although still valid)