下标超出范围c ++矢量擦除

时间:2015-10-11 21:52:10

标签: c++ class vector visual-studio-2015 erase

当我尝试从矢量中删除一个元素时,我得到一个超出范围矢量的错误下标

std :: vector用户;在我的.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());它不起作用,我得到同样的错误

1 个答案:

答案 0 :(得分: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);