can't remove duplicated objects from vector

I thought object 3 and 4 will be erased and this should output 1 and 2, but it gives me 1,2,3,4, why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>

using namespace std;

struct Human{
    int num;
    string name;
    Human(string name, int num):name(name),num(num){}
    friend bool operator==(const Human& a,const Human& b){
        
        return a.name == b.name;
    }
    
};



int main()
{
    
    vector<Human> a;
    Human b("Peter", 1), c("John", 2), d("Peter", 3), e("John", 4);
    a.push_back(b);
     a.push_back(c);
      a.push_back(d);
       a.push_back(e);
    
    a.erase(unique(a.begin(), a.end()), a.end());
    
    for(Human p:a){
        cout << p.num << endl;
    }
    

    return 0;
}

Last edited on
https://www.geeksforgeeks.org/difference-between-stdremove-and-vectorerase-for-vectors/

or, this:
a.erase(unique(a.begin(), a.begin()+2), a.end());

you have the erase params wrong, but the article shows the problems with erase if you want to dig into some info for future reference.
Last edited on
std::unique only removes CONSECUTIVE duplicates. Your nominally equal names are not next to each other in the vector.
Topic archived. No new replies allowed.