使用STL去除std::vector自定义结构体重复项

最近搞了一个小东西要去除一个vector中重复的项。是这样的:我用组播搜索设备,得到设备IP信息、版本号信息,等,但有时会接收到多个相同IP设备的信息,因此要过滤掉重复的IP。我使用vector存储每台设备信息,包括IP、版本号,因此需要使用结构体。另外,要对这些设备IP进行排序,让其IP顺序排列。

抽象出来,就是对一个包括结构体的vector进行排序、过滤重复项。参考网络资源,做了实现。
源码如下:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <vector>
#include <string>
#include <algorithm>

#include <stdio.h>

class foobar
{
public:
std::string token;
std::string item;
int number;

// 重载操作符
bool operator<(const foobar& rhs) { return (*this).token < rhs.token;};
bool operator>(const foobar& rhs) { return (*this).token > rhs.token;};
bool operator==(const foobar& rhs) { return (*this).token == rhs.token;}

};

bool sort_token(const foobar& s1, const foobar& s2)
{
return s1.token.compare(s2.token) < 0;
}

int main(int argc, char* argv[])
{
std::vector<foobar> vFoo;

foobar tmp;
tmp.token = "osd_1";
tmp.item = "OSD11111";
tmp.number = 1;
vFoo.push_back(tmp);

tmp.token = "osd_0";
tmp.item = "OSD111111";
tmp.number = 0;
vFoo.push_back(tmp);

tmp.token = "osd_2";
tmp.item = "OSD22222";
tmp.number = 2;
vFoo.push_back(tmp);

tmp.token = "osd_3";
tmp.item = "OS3330";
tmp.number = 3;
vFoo.push_back(tmp);

tmp.token = "osd_4";
tmp.item = "OS444444444444444";
tmp.number = 4;
vFoo.push_back(tmp);

tmp.token = "osd_1";
tmp.item = "OS5555555554444";
tmp.number = 5;
vFoo.push_back(tmp);

printf("before sort: \n");
for (unsigned int i = 0; i < vFoo.size(); i++)
{
printf("token: %s font: %d item: %s\n", vFoo[i].token.c_str(), vFoo[i].number, vFoo[i].item.c_str());
}

std::sort(vFoo.begin(),vFoo.end(),sort_token); // 先排序
// 去除重复项
std::vector<foobar>::iterator unque_it = std::unique(vFoo.begin(), vFoo.end());
vFoo.erase(unque_it, vFoo.end());

printf("after unque: \n");
for (unsigned int i = 0; i < vFoo.size(); i++)
{
printf("token: %s font: %d item: %s\n", vFoo[i].token.c_str(), vFoo[i].number, vFoo[i].item.c_str());
}
return 0;
}