Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to use STL-set

0 views
Skip to first unread message

johnnyzhou

unread,
Dec 15, 2009, 9:26:38 PM12/15/09
to
Hi, folks :

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

Jonathan Lee

unread,
Dec 15, 2009, 11:31:09 PM12/15/09
to
On Dec 15, 9:26 pm, johnnyzhou <0121...@163.com> wrote:
> Hi, folks :
>
>   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:

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

Sam

unread,
Dec 16, 2009, 7:07:01 AM12/16/09
to
johnnyzhou writes:

> Hi, folks :
>
> I would like to use set template class to sort a set of data

Yes, and you already posted the same question yesterday, and you already
received an answer.

Joe Gottman

unread,
Dec 16, 2009, 7:12:21 AM12/16/09
to

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

0 new messages