user2935569
user2935569

Reputation: 347

remove duplicates entry in vectors

I am trying to add objects using class(Sample),sort my vector and after that remove duplicates entries in my vector.

my codes (this is just part of my codes in my program)

vector<Sample> sampleVector;
sort(sampleVector.begin(), sampleVector.end());
sampleVector.erase(std::unique(sampleVector.begin(),sampleVector.end(),sampleVector.end()));

but however it when I tried to run my program it shows this error.

Type 'std::__1::__wrap_iter<Sample *>' does not provide a call operator

and I realized that most likely the error is caused by this line

sampleVector.erase(std::unique(sampleVector.begin(),sampleVector.end(),sampleVector.end()));

What should I do so that I can make it work to remove duplicate entries in my vector? thanks in advance

Another thing I have tried but it's not working.

bool myfunction (Sample *i,Sample *j) {
   return (i==j);
}

std::vector<Sample>::iterator it;
vector<Sample> sampleVector;
it = std::unique(sampleVector.begin(), sampleVector.end(),myfunction);   
for (it=sampleVector.begin(); it!=sampleVector.end(); ++it) {
            std::cout << *it << " "; <-- error must change it to &*it
}

Upvotes: 1

Views: 140

Answers (3)

battery
battery

Reputation: 522

Another possibility worth considering is that you could put the sorted elements into an std::set. That will retain the sorted ordering and ensure item uniqueness.

Upvotes: 0

Tiger Lu
Tiger Lu

Reputation: 1

I think you can try this code below

bool myfunction (int i, int j) {
     return (i==j);
}
std::unique (myvector.begin(), myvector.end(), myfunction);
std::cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it){
    std::cout << ' ' << *it;
}
std::cout << '\n';

Hope it will help!

Upvotes: 0

paddy
paddy

Reputation: 63481

Misplaced parenthesis. Correction:

sampleVector.erase( std::unique(sampleVector.begin(),sampleVector.end()),
                    sampleVector.end() );

I don't blame you for getting caught out. C++ compiler errors are heinous.

Upvotes: 2

Related Questions