2011-12-06 10 views
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の使用を検討する必要があります。 –

答えて

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)予想時間がかかりますが、半分定数。

+0

ありがとう、それは私のために働く。 – user1081481

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

これは、任意の容器から 条件付き除去要素に適用され、より一般的なパターンに従います。

関連する問題