remove duplicates entry in vectors

2020-04-21 00:18发布

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
}

标签: c++
3条回答
小情绪 Triste *
2楼-- · 2020-04-21 00:51

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.

查看更多
Deceive 欺骗
3楼-- · 2020-04-21 01:03

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.

查看更多
家丑人穷心不美
4楼-- · 2020-04-21 01:11

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!

查看更多
登录 后发表回答