user1081481
user1081481

Reputation: 55

deleting a key- value pair from a map using value

i want to delete a key-value pair from a map but my problem is that i have the value and not the key. How can i delete a key-value pair from the map using a "value". And the value what i have is unique in the map.

my code snippet:

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 ;
}

will this delete the key-value pair??

Upvotes: 3

Views: 2216

Answers (2)

James Kanze
James Kanze

Reputation: 153919

Yes. A more idiomatic solution would be to use the return value of erase to update the iterator when there's a match:

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

This follows the more general pattern, which is applicable to conditionally removing elements from any container.

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363577

Yes, this should work. But since the value is unique, you don't need to complete the iteration.

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;
        }
}

This still takes O(n) expected time, but with half the constant.

Upvotes: 2

Related Questions