迭代器通过引用set / map迭代器传递而不是dereferencable

时间:2017-01-20 12:11:47

标签: c++ dictionary reference iterator

我在通过引用传递迭代器时遇到了一些麻烦。在程序中,我有三个类:包含std :: map>的类A;作为私人会员。 B级将A级作为私人成员。并且在其构造函数中接收类B的类C.在类C中,我试图检索指向地图的迭代器,如下所示:

class A(){
   private: 
        std::map<std::vector<>> theMap;
   public:
        void theMap_access() {std::string to_access , std::map<std::vector<>>::iterator &it){
        it =  theMap.find(to_access);
        it-> first; //OK
   }         
};

class B(){
   private: 
        A a;
   public: 
        A A_access(){return a;}
};

class C(B &b){
   public: 
       std::map<std::vector<>>::iterator it;
       std::string to_access = "test";
       B.A_access().theMap_access(to_access, it);
       it-> first; //KO
};

当我执行此代码时,我确信&#34;测试&#34;在地图上。因此,当我在A类中取消引用它时,代码运行正常,我得到它 - &gt; first =&#34; test&#34;。但是在通过引用将它传递回C类之后,我得到了这个错误:set / map iterator not dereferencable。我假设一旦传回的迭代器没有指向它在A类中指向的东西。你能解释一下我为什么以及如何解决这个问题?非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

  

我收到此错误:set / map iterator not dereferencable。

这是因为A返回此处使用的B.A_access对象:

B.A_access().theMap_access(to_access, it);

执行上述行后

不再存在。因此,您设置的迭代器指的是不存在的map,因为map也已消失。

原因是B.A_access()返回A对象的副本,而不是包含A的实际std::map对象你正试图用。

如果您想使用包含您想要操作的A的实际std::map对象,则A_access应该返回对A的引用,而不是A

所以修复应该是:

 A& A_access(){return a;}
相关问题