I would like to use set template class to sort a set of data
,following is the source code , please help me to check the issue:
struct dbItem
{
int size;
};
struct cmpItem
{
bool operator() ( const dbItem* a, const dbItem* b ) const {
if( a && b && a!=b ) return a->size < b->size ;
return false;
}
};
void mergeItems( dbItem *item ) {
set<dbItem*, cmpCell> cells;
list<dbItem*>::iterator it=item->children.begin();
for( ; it!=item->children.end(); ++it ) {
cells.insert( (*it) );
}
}
Thanks ~~~~
B,R
Johnny
Well, from what I can see
1) struct dbItem doesn't have a member called "children"
2) cmpCell is never declared (presumably an instance of cmpItem)
3) mergeItems() effectively does nothing since it deletes "cells"
before doing anything with it.
Beyond that I can't really tell what you are asking. Are you
trying to sort "children"? You should
- copy the sorted set ("cells") back over children, or
- use a set instead of a list for "children", or
- use a container that you can call std::sort on
--Jonathan
Your cmpItem::operator() does not work right if exactly one of the
pointers a, b is null. The relationship
!cmp(a,b) && !cmp(b, a)
needs to be an equivalence relationship, and as written it is not .If a
and c are non-null with non-equal sizes and b is null then
!(a,b) && !(b, a) is true and
!(b,c) && !(c, b) is true, but
!(a, c) && !(c, a) is false.
You should rewrite cmpItem as follows:
struct cmpItem
{
bool operator() ( const dbItem* a, const dbItem* b ) const {
if (!b) return false; // Nothing is less than null
else if (!a) return true; // Null is less than non-null
else return a->size < b->size;
}
};
Note that you don't have to check whether a == b. The usual test a->size
< b->size correctly returns false when a is equal to b.
Joe Gottman