demo1源码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct PushStreamIpAndPort
{
std::string ip="";
int port=0;
// 重载相等运算符 == :可不用
bool operator==(const PushStreamIpAndPort &other) {
return this->port == other.port && this->ip == other.ip;
}
PushStreamIpAndPort() {}
// 重载构造函数去快速赋值:可不用
PushStreamIpAndPort(const std::string t_ip, const int t_port)
{
ip = t_ip;
port = t_port;
}
};
int main() {
PushStreamIpAndPort a;
PushStreamIpAndPort b;
a.ip = "127.0.0.1";
a.port = 10000;
b.ip = "127.0.0.1";
b.port = 10000;
PushStreamIpAndPort c = PushStreamIpAndPort("127.0.0.1", 10001);
vector<PushStreamIpAndPort> v;
v.push_back(a);
v.push_back(b);
// if(a==b){
// cout<<"相等"<<endl;
// }else{
// cout<<"不相等"<<endl;
// }
auto it = std::find(v.begin(), v.end(), c);
if(it != v.end())
{
cout<<"在内部"<<endl;
}
else{
cout<<"不在内部"<<endl;
}
return 0;
}
demo2源码:自动排除相同值
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct PushStreamIpAndPort
{
std::string ip="";
int port=0;
// 重载相等运算符 ==
bool operator==(const PushStreamIpAndPort &other) {
return this->port == other.port && this->ip == other.ip;
}
PushStreamIpAndPort() {}
PushStreamIpAndPort(const std::string t_ip, const int t_port)
{
ip = t_ip;
port = t_port;
}
};
int main() {
PushStreamIpAndPort a("127.0.0.1", 10000);
PushStreamIpAndPort b("127.0.0.1", 10000);
PushStreamIpAndPort c("127.0.0.1", 10001);
vector<PushStreamIpAndPort> v;
// 检查要添加的元素是否已经存在于 vector 中
if (find(v.begin(), v.end(), a) == v.end()) {
v.push_back(a);
}
if (find(v.begin(), v.end(), b) == v.end()) {
v.push_back(b);
}
if (find(v.begin(), v.end(), c) == v.end()) {
v.push_back(c);
}
for (const auto &elem : v) {
cout << "IP: " << elem.ip << ", Port: " << elem.port << endl;
}
return 0;
}