代码之家  ›  专栏  ›  技术社区  ›  Amir Rachum

从映射返回迭代器的函数

  •  2
  • Amir Rachum  · 技术社区  · 14 年前

    map<K,V> 在c'tor中获取其值的变量,如下所示:

    class Foo {
        map<K,V> m;
        Foo (map<K,V>& newM) : m(newM) {}
        map<K,V>::iterator bar () { ... }
    }
    

    函数 bar 遍历映射 m

    std::map<K,V> map;
    //fill map
    Foo foo(map);
    map<K,V>::iterator it = foo.bar();
    

    我的问题是,此刻,它是否指向 map ? 或者是抄袭给 Foo.m 因此迭代器指向不同的映射?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Naveen    14 年前

    当您将映射复制到变量中时,它将指向新映射 m 在班级里。声明 m(newM) 在初始化列表中调用 std::map 类并将传递的映射的各个元素复制到destination映射中 bar 方法,它将从这个新映射返回迭代器。

    编辑 用于存储 作为参考:

    class Foo {
    public:
        map<int,int>& m; //Note: the change here, I am storing a reference
        Foo (map<int,int>& newM) : m(newM) {}
        map<int,int>::iterator bar () { return m.begin();}
    };
    
    
    int main()
    {
        std::map<int,int> map1;
        Foo foo(map1);
        map<int,int>::iterator it = foo.bar();
    
        if(it == map1.begin())
        {
            std::cout<<"Iterators are equal\n";
        }
    }
    
        2
  •  0
  •   Mark Ingram    14 年前

    迭代器将指向类中包含的映射 Foo . 当然,这不应该是一个问题,虽然你已经复制地图的类?

    我的意思是,我假设你会这样做:

    map<K,V> original;
    Foo foo(original);
    map<K,V>::iterator it = foo.begin(), itEnd = foo.end();
    for (; it != itEnd; ++it)
    {
      // Do something with *it
    }