tags:

views:

60

answers:

2

Hi. I have been looking for an effective solution to remove duplicates from a C++ list.

The list consists of pointers to a class object which has an attribute ID. I want to remove duplicates based on that ID.

for my purpose, the unique method of the STL list will work in which we can pass a BinaryPredicate. i.e.

void unique( BinPred pr );

I searched on the internet about how to use this method, n got an example in which we can declare a function returning boolean and use the "name" of that function as Binary Predicate.

But it's not working.

What actually is this binary predicate and how do i use it ? ... Any help will be appreciated. Here is the code snippet:

class SP_MDI_View {
..
..
bool removeDupli(SP_DS_Node*, SP_DS_Node*);
bool DoReductionGSPN(SP_DS_Node*, SP_ListNode*, SP_DS_Node*);
..
..
}
SP_MDI_View::DoReduction( ... ) {
 SP_ListNode setZ; // typedef list<SP_DS_Node*> SP_ListNode, where SP_DS_Node is some other class
 setZ.clear();
 setZ.merge(tempsubset);
 setZ.merge(setX);
 setZ.push_back(*cs_iter);
 setZ.unique(removeDupli); //Error here
}
bool SP_MDI_View::removeDupli(SP_DS_Node* first, SP_DS_Node* second) {
return ( (first->GetId())==(second->GetId()) );
}
A: 

You have to use unique on an ordered list. So the first thing that you must do is sort the list.

Zan Lynx
while sorting also, i have an overloaded sort function which uses binary predicate. the way am doing sort is: define a boolean function, use that as binary predicate. But it doesn't work.is this valid ?mylist.sort(same_integral_part);i mean same_integral_part is a function and we are passing it as same_integral_part ?
Gaurav Kalra
A: 

You could write a function like:

bool foo (int first, int second)
{ return (first)==(second) ); }

Also, you might need to declare the function as static if your using it in class.

Dave18
yes i tried doing it. then i didmylist.unique(foo);but the compiler says no matching function unique.
Gaurav Kalra
@Dave I have posted the source code above. Static thing says "cannot declare member function to have static linkage"
Gaurav Kalra
@Gaurav: `static` should only appear in the class declaration, not when defining the member function out-of-class.
Georg Fritzsche
Hey that worked! ... But I still have duplicates in the list ... Do I need to sort the list first ?
Gaurav Kalra
yes we need to :-) ... everything is now working as expected! ... thanks a lot @Georg and @Dave
Gaurav Kalra