2015-10-11 81 views
1

當我嘗試從矢量中刪除元素時,我得到的錯誤下標超出範圍矢量下標超出範圍C++矢量刪除

std :: vector users;在我.hh

void Server::read_client(int socket) 
{ 
int  ret; 
int  size; 
char buff[255]; 
std::string data = "Hello, world!"; 

size = 255; 
ret = recv(socket, buff, size, 0); 
if (ret == 0 || ret == SOCKET_ERROR) 
{ 
    std::cout << "Client [" << socket << "] disconnected." << std::endl; 

    for (int i = 0; i < this->users.size();) 
    { 
     if (this->users[i]->getId() == socket) 
     { 
      std::vector<User *>::iterator iter; 
      /*for (iter = this->users.begin(); iter != this->users.end();) 
      { 
       if ((*iter)->getId() == socket) 
       { 
        delete *iter; 
        closesocket(socket); 
        this->users.erase(iter); // crash here 
        return; 
       } 
       else 
        iter++; 
      }*/ 
      closesocket(socket); 
      delete this->users[i]; 
      this->users.erase(this->users.begin() + i); // crash here 
      return; 
     } 
     else 
      i++; 
    } 
    return; 
} 
} 

我不知道爲什麼它崩潰了......就算我users.erase(users.begin());它不起作用,我得到相同的錯誤

+0

請給一個[MCVE](https://stackoverflow.com/help/mcve) –

回答

1

由於STL已經爲您提供了所需的一切,因此無需編寫如此多的代碼。

首先,您可以使用std::vector<std::unique_ptr<User>>,忘記delete this->users[i]。然後你可以使用std::find_if來做這個骯髒的工作:

std::vector<std::unique_ptr<User>> users; 

int socket = ...; 
auto it = std::find_if(users.begin(), users.end(), [socket](const std::unique_ptr<User>& user) { return user->getId() == socket; }); 
users.erase(it);