DragonVet
DragonVet

Reputation: 409

Sorting in C++ using defined class

I'm kind of new at C++, so bear with me if you can. I'm trying to sort a vector full of nodes. In my .h file I have the following definition for a node:

class Node{
public:
    Node(int data);
    bool sortMe(const Node & n1, const Node & n2);
    int getData();

private:
    int nData;
};

In my .cpp file, I define the functions such as:

Node::Node(int data){
    this->nData = data;
}
bool Node::sortMe(const Node & n1, const Node & n2){
    return n1.nData < n2.nData;
}

and in main attempt to sort a vector with:

Node aNode(7);
Node bNode(90);
Node cNode(84);
std::vector<Node> arrayName;
arrayName.push_back(aNode);
arrayName.push_back(bNode);
arrayName.insert(arrayName.begin(), cNode);
std::sort(arrayName.begin(), arrayName.end(), &Node::sortMe);

I include algorithm and everything, I just can't figure out why it doesn't want to use that function to sort the data...

Thanks in advance!

Upvotes: 0

Views: 132

Answers (4)

BlackMamba
BlackMamba

Reputation: 10252

If you use C++11, you can use lambda.

std::sort(arrayName.begin(), arrayName.end(), [](Node& l, Node& r){ return l.getData() < r.getData(); });

Upvotes: 0

Steve
Steve

Reputation: 1510

The std::sort() need a reference of comparison function.

There will be two ways to implement the comparison function:

  • static member function A normal member function shall not be used since a member function must need a specific instance of its class.

class Node{

public:

static bool sortMe(const Node & n1, const Node & n2);

};

  • normal function(). Remove the 'bool sortMe(const Node & n1, const Node & n2);' out from the Node class to the main.cpp, the problem will be solved.

bool Node::sortMe(const Node & n1, const Node & n2){

   return n1.nData < n2.nData;

}

Upvotes: 0

4pie0
4pie0

Reputation: 29764

You can use boost::bind:

std::sort( arrayName.begin(), arrayName.end(),
                                         boost::bind(&Node::sortMe, this,_1,_2));

or make sortMe function static. Even better is to use a functor instead of a function (this will be faster):

class Node{
public:
    Node(int data);
    bool sortMe(const Node & n1, const Node & n2);
    int getData();
    struct doCompare
    { 
       bool operator()( const Node& n1, const Node& n2  )
       { 
            // comparison code
       }
    };

private:
    int nData;
};

std::sort( arrayName.begin(), arrayName.end(), Node::doCompare() );

Upvotes: 0

Peter Bloomfield
Peter Bloomfield

Reputation: 5766

sortMe() is currently declared as a member function. That means it needs to be called on a specific instance of the Node class, rather than being used as a standalone function.

To fix it, simply prefix the function declaration with static (only in the class header; not in the implementation). That means the function belongs to the class, not a specific instance.

Upvotes: 4

Related Questions