【问题标题】:I read map.erase(map.end()); deletes the last element of the map.But what's the last element? Is it based in the insertion order of elements?我读了 map.erase(map.end());删除地图的最后一个元素。但是最后一个元素是什么?它是基于元素的插入顺序吗?
【发布时间】:2016-06-10 15:32:08
【问题描述】:

我是初学者。假设我创建了

 map<int, node*> mp;

节点在哪里

struct node{
node *previous;
int key; // I have no idea why there is a key variable in this node
int value;
node *next
};

所以map有int键,指向一个双向链表的节点。

假设我按顺序插入了以下元素。

<key,(let corresponding node.value element be)>  
<5, 1>
<10,2>
<8, 3>  

所以双向链表看起来像:

1<->2<->3

现在,如果我想在现有节点之间插入一个节点值为 2,3 的新节点。所以我创建了一个新的地图元素。

<key,(let corresponding node.value element be)>  
<7, 4>  

并且(新调整的)双向链表看起来像:(根据我的要求)

1<->2<->4<->3

哪个元素会 mp.erase(mp.end());删除,为什么?

我写了一个示例程序,其中地图元素被删除了。为什么会这样?

仅供参考:我正在为 LRUcache 代码工作。

【问题讨论】:

  • map.erase(map.end()); 是一个错误; end-iterators 代表一个单一的状态(例如过去的结束或特殊状态)。地图不保留插入顺序;如果您删除地图的最后一个元素,那么它将是具有最大排序键的元素
  • @M.M 但它对我来说非常好用。它正在删除一个元素
  • 正如@M.M 所说map.erase(map.end()); 是一个错误 并导致未定义的行为:map.erase( map.end() )?std::map::erase [...]The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferencable) cannot be used as a value for pos.[...]
  • “我读了 map.erase(map.end()); 删除了地图的最后一个元素”。这是不正确的。你在哪里读到的?

标签: c++ dictionary


【解决方案1】:
map<int, node*> mp;
mp.insert(make_pair(5, nullptr));
mp.insert(make_pair(10, nullptr));
mp.insert(make_pair(8, nullptr));

std::map 内部按其键排序,默认升序,使用std::less&lt;Key&gt;。因此,第二个值(可以是任何值)无关紧要。

mp.erase(--mp.end());
// or
mp.erase(std::prev(mp.end(), 1));

应始终删除键为“10”的对,而不是您可能认为的键为“8”的对。

【讨论】:

    【解决方案2】:

    首先,map.end():

    返回一个迭代器,该迭代器引用地图中的过去的元素 容器。

    past-the-end 元素是一个虚拟元素(也就是说,它实际上并不存在)。它表示地图最后一个有效元素之后的元素。

    如果你问,为什么是虚拟元素? map.end() 不应该实际表示最后一个元素吗?

    这是因为大多数涉及 C++11 容器的操作,如 mapsetvector 等。将它们的操作指定为 [ ),这意味着无论何时为任何操作提供范围,该范围被解释为:包含第一个元素,不包含最后一个元素

    例如,[2,5) 表示必须在 2,3,4 上执行操作。

    其次,当您调用mp.erase(element) 时,此element 必须是有效且可取消引用的元素。但是您正在为它指定map.end()

    mp.erase(mp.end()) 不能工作。

    回到你的问题,TL;DR:

    地图没有记录插入顺序

    所以从末尾删除意味着删除地图中存在的最后一个元素,按键排序。

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 2015-04-20
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多