[英]iterator passed by reference set/map iterator not dereferencable
I am having some trouble with passing an iterator by reference. 我在通过引用传递迭代器时遇到了一些麻烦。 In the program, I have three classes: the class A that contains a std::map> as a private member.
在程序中,我有三个类:A类,其中包含一个std :: map>作为私有成员。 The class B holding the class A as a private member.
B类将A类作为私人成员持有。 And the class C that receives in its constructor the class B. In the class C, I am trying to retrieve an iterator pointing to the map as follows:
还有在其构造函数中接收到类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
};
When I execute this code, I am sure "test" is in the map. 当我执行此代码时,我确定“ test”在地图中。 So when I dereference it in class A, the code runs fine and I get it->first = "test".
因此,当我在类A中取消引用它时,代码可以正常运行,并且得到它-> first =“ test”。 But after passing it by reference back to class C, I get this error: set/map iterator not dereferencable.
但是在通过引用将其传递回C类之后,出现了以下错误:set / map迭代器不可取消引用。 I assume the iterator once passed back is not pointing to what it was pointing to in class A. Could you please explain me why and how I can fix that?
我认为迭代器一旦返回就没有指向它在A类中指向的对象。您能否解释一下原因以及如何解决该问题? Many thanks for your help.
非常感谢您的帮助。
I get this error: set/map iterator not dereferencable.
我收到此错误:set / map迭代器不可取消。
That is because the A
object that is being used here in the return of B.A_access
: 这是因为在
B.A_access
返回中使用的A
对象:
B.A_access().theMap_access(to_access, it);
no longer exists after the above line is executed. 执行上述行后不再存在。 So the iterator you set is referring to a non-existing
map
, since that map
also has gone away. 因此,您设置的迭代器引用的是不存在的
map
,因为该map
也已消失。
The reason why is that B.A_access()
returns a copy of the A
object, and not the actual A
object that contains the std::map
you're trying to use. 原因是
B.A_access()
返回A
对象的副本 ,而不是包含您要使用的std::map
的实际A
对象的副本 。
If you want to use the actual A
object that contains the std::map
you want to manipulate, then A_access
should return a reference to A
, not a copy of A
. 如果你想用实际的
A
包含对象std::map
要操作,那么A_access
应该返回一个引用A
,而不是复制A
。
So the fix should be: 因此,解决方法应该是:
A& A_access(){return a;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.