Re: std::set and operators
On 24 Mai, 08:55, Rune Allnor <all...@tele.ntnu.no> wrote:
Hi all.
I haev this application where I need to compare several sets.
The tasks include finding the intersection of two sets and
finding elements unique in each set.
It is a rather obvious idea to use operator+ to find the union
of two sets:
#include <set>
std::set<...> a, b, c;
c = a + b; // c contains the union of a and b
c = a - b; // c contains the elements unique to a
Many people are missing that kind of operators in the STL
and so on.
Is there a standard set of operators to do these sorts of things?
{ Look up set_union, set_intersection, set_difference,
and set_symmetric_difference in the standard library. -mod/sk }
yet as the moderator states (I guess this is a moderator's insertion)
the STL way of doing this is to use algorithms set_union etc. instead
of operators. These algorithms are able to perform set operations
not only on std::set but also on other containers, if they contain
sorted ranges [see e.g. Scott Meyers, Effective STL, Item 34].
This makes the STL more minimal (in terms of implementations of
algorithms) and at the same time more general (in terms of
availability
of algorithms for different containers)...
This design is very straight and fundamental to the STL's success.
On the other hand I personally find the work with set_[algorithms]
always a little clumsy and notational less elegant as an operator use.
So you might implement operators for std::sets yourself as
namespace::global functions using set_[algos] for implementing them.
If you like, you can use the set implementation of my Interval
Template
Library ITL which is compatible with std::set but implements +=, -=
and *= for union, difference and intersection in addition.
(download from http://sourceforge.net/projects/itl).
I refrained from implementing operators +, - and * though, because a
general purpose implementation of them can be very inefficient on
containers especially when used in nested expressions. This generates
temporary objects [see e.g. Scott Meyers, More effective c++, item
22].
Moreover, if you have o= versions of operators you can implement
their .o. cousins via templates in a very general way:
template<class T> const T operator + (const T& lhs, const T&rhs)
{ return T(lhs) += rhs; }
cheers
Joachim
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]