sorting

Hi,

I know one working solution of my sorting problem, but I am curious if there is a better way to handle this. Please share your opinion.


I have a class A, for which I am defining the operator <. However, this comparison function needs access of an object of other class B. I dont wish to store the object of (or even pointer of) B in the objects of class A. Instead, I am defining a global pointer to the object of B, which is assumed not null in the comparison.

1
2
3
4
5
6
7
8
9
10
11
B* objB = NULL;

bool A::operator< (const A &fv) const{

    if(objB == NULL)
        throw std::invalid_argument("A::operator<  -- Cant compare since objB is NULL!");

    /* ----
       comparison logic 
    */
}


However, what this means is that when creating a set of objects of A, I need to set the pointer objB.

1
2
3
4
5
6
objB = some value

set<A> setA;
/* ----
 start inserting values
*/


This gets messy, especially if the code spans multiple files, and i need to use

 
extern B* objB


What would be a more elegant way to handle such a case ?

Don't use the operator< but a comparison class.
http://cplusplus.com/reference/set/set/set/
set<A, compare> setA( compare(objB) );

Every set has its own compare object.
According to your needs, the objB can be shared.
Great. Thanks.
Topic archived. No new replies allowed.