About STL set/set algorithms

Discuss all kind of algorithms and data structures from their mathematical and programming sides.

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

About STL set/set algorithms

Postby GeekDog » Mon Jun 13, 2005 12:38 pm

I've been looking at the std::set, or at least the SGI version of it, and I'm a bit confused.

According to the main set page, if you're generating a set of objects that don't have an operator< defined, you need to provide a class that allows you to compare the objects, in order to implement the strict weak ordering that set requires.

However, according to, for example, the set_intersection() page says that when using an algorithm such as set_intersection, if there is no operator< available, you need to provide a function object that allows comparison between the objects.

My question is basically: why in one case is a class required, and in the other a function object? Am I missing something fundamental?

Thanks to anyone who can shed any light on this! :wtf:
User avatar
GeekDog
 
Posts: 1160
Joined: Sun Sep 28, 2003 1:42 pm
Location: UK

Postby Beer Hunter » Mon Jun 13, 2005 4:05 pm

The first one is referring to a template parameter, like "MyClass" in "set<int, MyClass>". The second one is referring to a function parameter, like "MyClass()" in "set_intersection(foo, bar, MyClass())". The first refers to a type and the second refers to an instance of the type.

Actually, the first page doesn't even say that it needs to be a class. In fact, you can use function pointers with set<>:[syntax="cpp"]bool compare_ints(int a, int b) { return a < b; }
set<int, bool(*)(int,int)> myset(compare_ints); // valid C++[/syntax]
User avatar
Beer Hunter
 
Posts: 912
Joined: Sat Dec 13, 2003 7:12 pm
Location: Australia

Postby GeekDog » Tue Jun 14, 2005 4:57 am

Thanks Beer Hunter. I am aware of the difference between template parameters and function parameters, just slightly confused why they couldn't have written it so both cases took the same type. The main thing I meant to ask was whether there was an implementation/syntactically-relevant reason that these two-closely related things are called differently. In my opinion, it would be more straightforward from the user's point of view if both took a class, or both took a function pointer, as you could then write one function/class and pass that in both cases.

I didn't realise you could pass a function pointer to the first version, being able to pass the same thing to both makes things slightly simpler for me...
User avatar
GeekDog
 
Posts: 1160
Joined: Sun Sep 28, 2003 1:42 pm
Location: UK


Return to Algorithms & Data Structures

Who is online

Users browsing this forum: No registered users and 1 guest