我使用以下结构:
hash_map<string, list<time_t>>
当我最初用从文本文件中读取的信息填充散列映射时,我可以毫无问题地将元素插入到那些 time_t 列表中。
hash_t::iterator it = hash.find(origen);
if (it != hash.end())
{
(*it).second.push_front(fecha);
}
else
{
list<time_t> lista(1, fecha);
hash.insert(make_pair(origen, lista));
}
如您所见,如果键字符串不在表中,我将创建一个包含一个 time_t 值的列表并将该对插入到表中。在同一键的后续 apeareances 上,我只是将新的 time_t 元素推到已经存在的列表上并且工作正常。
我现在想做相反的事情:删除那些列表中的元素。
hash_t::iterator it = hash.find(origen);
if (it != hash.end())
{
list<time_t> lista = (*it).second;
list<time_t>::iterator it2 = lista.begin();
bool found = false;
while(it2 != lista.end() && !found)
{
time_t fecha2 = *it2;
if (abs((int) difftime(fecha, fecha2)) <= 2)
{
found = true;
lista.erase(it2);
}
else ++it2;
}
}
此代码不会从这些列表中删除元素。
我想问题是从这一行开始的:
list<time_t> lista = (*it).second;
变量 lista 是否具有我可以从 hash_map 或它的拷贝中获得的相同列表?如果它是拷贝,我不明白它不起作用的原因。但是,我仍然不明白为什么它确实可以插入元素。
(*it).second.push_front(fecha);
有没有一种方法可以使用类似于我正在做的方法从列表中删除元素,或者我是否必须将 hash_map 的整个结构更改为类似的东西
hash_map<string, list<time_t>*>
非常感谢您
最佳答案
erase()
代码对列表的拷贝进行操作,而不是对 hashmap
中的实际列表进行操作。这将创建一个拷贝:
list<time_t> lista = (*it).second;
改用引用:
list<time_t>& lista = (*it).second;
push_front()
正确运行,因为没有复制,代码直接访问 hashmap
中的列表:
(*it).second.push_front(fecha);
关于c++ - 从 hash_map 中的列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11141391/