0

Suppose I have a set std::set<*int> and I want the elements to be sorted by the integer to which they point rather than the pointer type; is there some standard comp function I can use from the std library? If not, how would I declare such a set?

I'm guessing I would have to do define my own comparison function but how does that look in practice?

quant
  • 21,507
  • 32
  • 115
  • 211
  • May I ask why you'd have a set of pointers to single ints? – John Zwinck Oct 15 '13 at 12:08
  • @JohnZwinck I wouldn't, I actually have a set of pointers to classes with their own `<` operators, but I thought this would be a simplified analogy to my problem. – quant Oct 15 '13 at 12:09
  • 1
    Given all that, this is a nearly exact duplicate of the question I just linked. You'll find its solution works for you too. – John Zwinck Oct 15 '13 at 12:11
  • @JohnZwinck that's similar, but it applies to a list which is sorted by `std::sort()`. In my case I need to declare an object of type `std::set<*int,Comp>`, and I don't know how to do that! – quant Oct 15 '13 at 12:13
  • Please don't mark this to close; that question is not related to this one, at least not as far as I can tell. If it is, please tell me why as I would love to know! – quant Oct 15 '13 at 12:14
  • 1
    I found a better duplicate. – juanchopanza Oct 15 '13 at 12:18

1 Answers1

3

Using the solution from Sort a std::list<myclass*> with myclass::operator<(myclass &other) it goes like this:

template <typename T>
struct PComp
{
    bool operator ()(const T* a, const T* b) const
    {
       return *a < *b;
    }
};

std::set<int*, PComp<int> > my_set;
Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436