-4

I am trying to change the order of a set in a particular configuration :

a customObject has the following form

class CustomObject{
public:

...
std::set<CustomObject*> container;

};

and I would like to keep permanently the property telling that the container is sorted in the following order :

elt1 & elt2 are elements of container, and elt1 < elt2 iff elt1.container.size()<elt2.container.size()

I know I have to use

struct cmpStruct {
    bool operator() (int const & lhs, int const & rhs) const
  {
    return lhs > rhs;
  }
};

as described Is the std::set iteration order always ascending according to the C++ specification?

But I don't know how to do to access the "this" inside the structure

Thanks a lot for your help

Community
  • 1
  • 1
  • 1
    what `this` do you want to access? I guess you want to compare two `CustomObject`s instead of `int`s. Once you change the signature of your `cmpStruct` I think you will know the answer yourself (tbh I dont understand the question at all) – 463035818_is_not_an_ai Mar 23 '17 at 19:42
  • How is comparing two `int`s related to your class `CustomObject`? – R Sahu Mar 23 '17 at 19:56

1 Answers1

0

Something like that?

class CustomObject{
public:
    CustomObject(int _x) : x(_x) {};
    int x;
};

struct cmpStruct {
    bool operator() (const CustomObject*  lhs, const CustomObject*  rhs) const
    {
        return lhs->x > rhs->x;
    }
};

int main(int argc, char* argv[])
{
    std::set<CustomObject*, cmpStruct> container;

    CustomObject a(10);
    CustomObject b(20);
    CustomObject c(5);

    container.insert(&a);
    container.insert(&b);
    container.insert(&c);

    for(auto co : container) {
        std::cout << co->x << std::endl;
    }
    return 0;
}

Output:

20
10
5
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • i know it is difficult to understand the question, but as I understood OP has a container of `CustomObject`s and wants to sort them according to their `container`s size (ie `lhs->container.size() > rhs->container.size()`) – 463035818_is_not_an_ai Mar 23 '17 at 20:07
  • I am not sure of what the line CustomObject(int _x) : x(_x) {}; does but yes, tobi303 expressed it right, I want to sort by container.size(). your answer is right if we add this little change, thanks to both of you – Mickael Wajnberg Mar 26 '17 at 13:47