【问题标题】:std::map multiple iterators, deletion and its valuestd::map 多个迭代器、删除及其值
【发布时间】:2014-06-18 12:02:59
【问题描述】:
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include <stdlib.h>

using namespace std;

class Fix
{

};

int main() 
{
    map<int, Fix *> m;

    Fix * f = new Fix();
    m.insert( make_pair( 2, f) );

    m.insert( make_pair( 3, f) );

    map<int, Fix *>::iterator it = m.find(2);
    map<int, Fix *>::iterator it1 = m.find(2);


    m.erase(it);

    // Will Create problem 
    // m.erase(it1);

    // Still value is there
    // So from the map node, iterator copy its value ?
    printf("%d\n", it->first);
    printf("%d\n", it1->first);

}  

我有一个 Map 包含两个条目,还有两个指向同一个条目的迭代器。 使用 Iterator1 从地图中删除一个条目。删除后仍然 Iterator1 和 Iterator2 持有价值。

问题

  1. Iterator 是否指向 Map 的节点(红黑树)
  2. 迭代器在迭代时是否同时处理节点中的键和值?因此,即使在从地图中删除条目后,它也会保留该值。

【问题讨论】:

    标签: c++ map stl iterator


    【解决方案1】:

    对于std::map::erase 在迭代器上使用this method 具有以下效果:

    • 从容器中移除指定元素

    • 对已擦除元素的引用和迭代器无效。其他引用和迭代器不受影响。

    因此,在删除 it 后,您将无法使用 it1,即使 it1 仍然可以巧合地指向“现在无效”的先前记忆。

    【讨论】:

      【解决方案2】:

      请标记接受的答案。

      bits_international 在他的解释中是正确的,将您的 main 函数中的代码更改为以下代码。

      map<int, Fix *> m;
      
      Fix * f = new Fix();
      m.insert( make_pair( 2, f) );
      
      m.insert( make_pair( 3, f) );
      
      map<int, Fix *>::iterator it = m.find(2);
      
      it = m.erase(it); //you can reuse it after this call
      map<int, Fix *>::iterator it1 = m.find(2);
      
      it1 = m.erase(it1); //you can reuse it1 after this call
      
      printf("%d\n", it->first);
      printf("%d\n", it1->first);
      

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 2011-06-03
        • 2014-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        • 2012-08-28
        • 1970-01-01
        相关资源
        最近更新 更多