【问题标题】:Function that returns iterator from a map从地图返回迭代器的函数
【发布时间】:2010-08-03 09:07:42
【问题描述】:

我有一个带有 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 并因此迭代器指向不同的地图?

【问题讨论】:

    标签: c++ map std


    【解决方案1】:

    它将指向新地图,因为您将地图复制到类的 ctor 中的变量 m 中。初始化列表中的语句m(newM) 调用std::map 类的复制构造函数,并将传递的映射的各个元素复制到目标映射m。因此,当您调用 bar 方法时,它将从这个新映射中返回迭代器。

    编辑 将std::map 存储为参考的示例代码:

    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";
        }
    }
    

    【讨论】:

    • +1。补充一点:如果是这样,Foo 构造函数应该接受一个 const 引用。
    • @Naveen 是否有可能以某种方式使其返回指向原始地图的指针 - 使用引用而不是指针?
    • @Amir Rachum:是的,如果你只在你的类中存储一个引用,你可以将迭代器返回到原始容器。但请注意,这是有风险的,因为您必须确保您的原始地图在foo 对象被销毁之前不会超出范围。否则,您最终会得到一个无效的引用,并且您的代码的行为将无法预测。
    • @Naveen 你能展示一个简单的语法示例吗?我对引用有点困惑。
    【解决方案2】:

    迭代器将指向您的类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
    }
    

    【讨论】:

    • 所有权尚未转让 - 已制作副本。
    猜你喜欢
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2021-06-11
    • 2022-10-02
    • 1970-01-01
    • 2016-08-17
    相关资源
    最近更新 更多