STL Vector and unique/sort algorithms

S

Suma

A newbie question :

I have a vector of objects(pointers) . I have a function which
overloads the less than operator . I can sort the objects without a
problem. However when I pass the same function as an arg to the unique
function, I still see the duplicate objects.
Shouldnt unique be aple to operate with just the less_than overload-
since if both the predicates constant1 < constant2 and constan2 <
constant1 return false implies equality?
What am i assuming wrongly?
Pseudo code

Input:
class CPerson
{
int age;
int salary
}

bool less_than(CPerson* p1,CPerson*p2)
{

}

vector<CPerson*> oArray;
..
..
..
sort(oArray.begin(),oArray.end(),less_than())


iterator new = unique(oArray.begin(),oArray.end(),less_than())

begin to new is not unique
 
N

Neelesh Bodas

Suma said:
A newbie question :

I have a vector of objects(pointers) . I have a function which
overloads the less than operator . I can sort the objects without a
problem. However when I pass the same function as an arg to the unique
function, I still see the duplicate objects.
Shouldnt unique be aple to operate with just the less_than overload-
since if both the predicates constant1 < constant2 and constan2 <
constant1 return false implies equality?
What am i assuming wrongly?
Pseudo code

Input:
class CPerson
{
int age;
int salary
}

bool less_than(CPerson* p1,CPerson*p2)
{

}

vector<CPerson*> oArray;
.
.
.
sort(oArray.begin(),oArray.end(),less_than())


iterator new = unique(oArray.begin(),oArray.end(),less_than())

begin to new is not unique

Not sure, but just two points -
1) std::unique removes only the adjacent duplicate elements. It doesnot
remove duplicates all over the array. (Of course that should not be a
probelem here since vector is already sorted)
2) std::unique uses std::adjacent_find which in turn uses operator==.
std::Operator== is not implemented in terms of std::eek:perator<, so the
way equality is tested is not necessarily by using operator<.

As an aside, even for a pseudocode, it is a bad idea to use a reserved
word like "new" to name a variable (specifically when you can convey
the same idea by using some other name)
 
N

Neil Cerutti

A newbie question :
sort(oArray.begin(),oArray.end(),less_than())


iterator new = unique(oArray.begin(),oArray.end(),less_than())

Don't use less_than as a predicate to unique. You need to use,
for example, equal_to. The binary predicate version will remove
those elements where binary_pred(*i, *(i-1)) == true.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top