使用value从映射中删除键值对

deleting a key- value pair from a map using value

本文关键字:删除 键值对 映射 value 使用      更新时间:2023-10-16

我想从映射中删除一个键值对,但我的问题是我有值而没有键。如何使用"值"从映射中删除键值对。我所拥有的价值在地图上是独一无二的。

我的代码片段:

int Clientqueues::addClient(string ipaddress, string sessionid)
{
    clientsWithNoLogin.insert(pair<string,string>(ipaddress,sessionid));
    return 0;
}
void Clientqueues::deleteClient(string sessionid)
{
    map<string, string>::iterator i,current;
   for(i = clientsWithNoLogin.begin() ;i!= clientsWithNoLogin.end();)
   {
    current = i;
    ++i;
    if((current->second) == sessionid) clientsWithNoLogin.erase(current);
   }
   return ;
}

这会删除键值对吗??

是的,这应该有效。但是,由于该值是唯一的,您不需要完成迭代。

void Clientqueues::deleteClient(string sessionid)
{
    for (map<string, string>::iterator i(clientsWithNoLogin.begin());
         i != clientsWithNoLogin.end(); ++i)
        if (i->second == sessionid) {
            clientsWithNoLogin.erase(i);
            break;
        }
}

这仍然需要O(n(的预期时间,但需要常数的一半。

是。更惯用的解决方案是使用的返回值erase在匹配时更新迭代器:

std::map<std::string, std::string>::iterator current
        = clientsWithNoLogin.begin();
while ( current != clientsWithNoLogin.end() ) {
    if ( current->second == sessionId ) {
        current = clientsWithNoLogin.erase( current );
    else
        ++ current;
}

这遵循更通用的模式,适用于有条件地从任何容器中移除元素。