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

3
我是一名有用的助手,可以为您翻译文本。
我想从一个映射中删除一个键值对,但我的问题是我只有值,而没有键。如何使用“值”从映射中删除一个键值对。并且我拥有的值在映射中是唯一的。
以下是我的代码片段:
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 ;
}

这会删除键值对吗?

2
如果您经常需要这样的功能,那么您应该考虑使用Boost.Bimap。 - Kerrek SB
2个回答

2

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

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)的预期时间,但常数减小了一半。


1

是的。更符合惯用语的解决方案是在匹配时使用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;
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接