使用value从映射中删除键值对
deleting a key- value pair from a map using value
我想从映射中删除一个键值对,但我的问题是我有值而没有键。如何使用"值"从映射中删除键值对。我所拥有的价值在地图上是独一无二的。
我的代码片段:
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;
}
这遵循更通用的模式,适用于有条件地从任何容器中移除元素。
相关文章:
- 在C++中共享键值对的最佳方式
- 使用无序映射在STL中存储键值对
- c++同一个键的多个键/值对
- C++中的键值对:<val1, val2> 键<frequency>与值一样
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- 读取数组中每个对象的所有键值对
- 这C++ unordered_map怎么有四个值?我以为这是一个键值对
- 使用 k 个键值对为零的存储桶初始化 c++14 unordered_map
- 从配置文件qsetting中删除键/值对
- 如何使用卡萨布兰卡在现有的web::json::value对象中附加新的键值对?
- 是否可以创建字符串和原子<int>键值对的unordered_map?
- 检索16k键值对的最快方法
- 将键值对文件读入 std::map
- 为什么用Spirit解析一个空行会在映射中产生一个空的键值对
- 从unordered_map C++中删除键/值对
- 如何将键值对引用从一个映射复制到同一类型的另一个映射
- 从键值对进行双向查找
- 如何从映射中修改键值对的值,而我不知道该键是否存在于映射中
- 提升精神 - 跳过键值对中不需要的行
- 使用value从映射中删除键值对