Re: Set with Sort routine
On Tue, 27 Jun 2006 08:10:22 -0500, "Bruce Chastain"
<bchastain@XNOSPAMXhyperfeed.com> wrote:
I'm trying to create a set with my sort criteria specified, using MS
Developer Studio 7 and I can't get the syntax correct. Everything I try
creates a compile time error. Here's the basics:
#include <set>
using namespace std;
typedef struct {
int value;
} MyElem;
This is C++, so write:
struct MyElem
{
int value;
};
Even in C, you should specify a tag, e.g.
// C only
typedef struct MyElem
{
int value;
} MyElem;
bool MyCompare( const MyElem& elem1, const MyElem& elem2 )
{
return( elem1.value < elem2.value );
}
void main()
{
set<MyElem, MyCompare> database;
}
The last line compiles with an error:
misc2.cpp(30) : error C2923: 'std::set' : 'MyCompare' is invalid as template
argument '#2', type expected
misc2.cpp(23) : see declaration of 'MyCompare'
Any clues? I've also tried:
The error message says "type expected", and that is indeed what you need to
supply:
set<MyElem, bool(*)(const MyElem&, const MyElem&)> database(MyCompare);
You also have to tell it which function to use, hence the ctor argument.
You have two alternatives:
1. Define operator< for MyElem, and then you will automatically take
advantage of std::less, e.g.
bool operator<(const MyElem& elem1, const MyElem& elem2)
{
return elem1.value < elem2.value;
}
set<MyElem> database;
2. Define a class to perform the comparison, e.g.
struct Comp
{
bool operator()(const MyElem& elem1, const MyElem& elem2)
{
return elem1.value < elem2.value;
}
};
set<MyElem, Comp> database;
Both these alternatives may help the compiler inline the comparisons, and
they are preferred to using function pointers.
--
Doug Harrison
Visual C++ MVP