如何在数组中找到重复项?我最多放了3 Clients
。当我有2 Client
时,它会使用传入的Client
更新现有的Client
,但是当我有3 Client
时,它会停止更新现有的Client
1}} s与传入的Client
s。服务器仍然接收数据,Client
仍然发送数据,但它不会更新数据。
我在这里看了一些关于数组重复的帖子,但我无法理解它们。
我认为它与j < 3
或i < 3
有关,但我不太确定。如何正确检测重复项并将其删除?
//Initialize Client
Client clients[3]; //Max of 3 clients
initClient(clients);
while (1){
for(int i = 0; i < 3; i++) {//Existing Client
for(int j = i; j < 3; j++) {//Incoming Client
if(j != i) {
if (clients[i].port == clients[j].port){ //If incoming port has the same port as existing, then update
clients[i].x = clients[j].x;
clients[i].y = clients[j].y;
clients[i].channel = clients[j].channel;
clients[i].data = clients[j].data;
clients[i].len = clients[j].len;
clients[i].maxlen = clients[j].maxlen;
clients[i].status = clients[j].status;
clients[i].host = clients[j].host;
clients[i].port = clients[j].port;
clients[i].address = clients[j].address;
clients[i].present = clients[j].present;
//Remove the incoming client
clients[j].present = false;
clients[j].alive = false;
objectCount2--;
}
}
}
}
}
答案 0 :(得分:0)
除了忘记检查元素是否被删除之外,你几乎做得很好。
for( uint idx = 0; idx < clients.size() - 1; ++idx)
{
for( uint jdx = 1 + idx; jdx < clients.size(); ++jdx )
{
if( clients[idx].not_removed()
&& clients[jdx].not_removed()
&& clients[idx].match( jdx ) )
{
clients[idx].assign( jdx );
clients[jdx].remove();
}
}
}
类似于冒泡排序。您应该考虑始终保持您的结构有序。