POV-Ray : Newsgroups : povray.off-topic : C++ questions : Re: C++ questions Server Time
7 Sep 2024 09:20:25 EDT (-0400)
  Re: C++ questions  
From: Warp
Date: 28 Sep 2008 09:39:45
Message: <48df8921@news.povray.org>
Orchid XP v8 <voi### [at] devnull> wrote:
> Question: What happens if your class doesn't have the comparison operator?

  If there's no way you can add an operator<() for your class, then you
can give std::set a comparator. A comparator is a functor used to compare
two elements of the same type (it takes two parameters of the type in
question, and returns a boolean telling if the first parameter is less
than the second parameter). This happens, for example, like this:

struct MyComparator
{
    // Note that this member function must be of 'const' type:
    bool operator()(const MyClass& lhs, const MyClass& rhs) const
    {
        return /* is lhs less than rhs? */;
    }
};

int main()
{
    // Make a type alias, to simplify the usage:
    typedef std::set<MyClass, MyComparator> TheSetType;

    TheSetType theSet;
    ...
}

  If your comparator has some state which may be different between sets,
you can give an initialized instance of your comparator to the set:

    TheSetType theSet(MyComparator(initialization, values));

  It is also possible to create a comparison function and use as a functor
(as you might remember). However, the syntax of the TheSetType definition
becomes a bit complicated.

  By the way, std::set (as well as std::map) *always* takes a comparator
(rather than using the < operator directly). When none is specified, the
default comparator used is std::less which, by template magic, makes it
completely equivalent to comparing the elements with the < operator
directly.

  This is good to know because you might sometimes want the elements
sorted in some other way. For example, if you want to sort them in
decreasing order, you can use the std::greater comparator (provided
by the standard C++ library). For example:

    typedef std::set<int, std::greater<int> > TheSetType;

  All integers added to this set will be in decreasing order rather than
in increasing one.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.