C++ 由引用集/映射迭代器传递的迭代器不可取消引用
我在通过引用传递迭代器时遇到了一些问题。在这个程序中,我有三个类:包含std::map>作为私有成员的类A。B类作为私人成员持有A类股份。类C在其构造函数中接收类B。在类C中,我试图检索指向映射的迭代器,如下所示:C++ 由引用集/映射迭代器传递的迭代器不可取消引用,c++,dictionary,reference,iterator,C++,Dictionary,Reference,Iterator,我在通过引用传递迭代器时遇到了一些问题。在这个程序中,我有三个类:包含std::map>作为私有成员的类A。B类作为私人成员持有A类股份。类C在其构造函数中接收类B。在类C中,我试图检索指向映射的迭代器,如下所示: class A(){ private: std::map<std::vector<>> theMap; public: void theMap_access() {std::string to_access , s
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
};
A类(){
私人:
std::映射主题图;
公众:
void theMap_access(){std::string to_access,std::map::iterator&it){
it=映射查找(以访问);
it->first;//好的
}
};
B类(){
私人:
A A;
公众:
A_access(){返回A;}
};
C类(B&B){
公众:
std::map::it迭代器;
std::字符串到_access=“test”;
B.A_access().theMap_access(to_access,it);
it->first;//KO
};
当我执行这段代码时,我确信“test”在映射中。因此,当我在类A中取消引用它时,代码运行良好,我得到它->first=“test”.但是在通过引用将其传递回类C之后,我得到了以下错误:set/map迭代器不可解引用。我假设曾经传递回的迭代器没有指向它在类A中所指向的内容。您能解释一下为什么以及如何修复它吗?非常感谢您的帮助
我得到这个错误:set/map迭代器不可解引用
这是因为在返回B.A\u访问时使用的A
对象:
B.A\u access().theMap\u access(to\u access,it);
执行上述行后不再存在。因此,您设置的迭代器引用的是不存在的map
,因为该map
也已消失
原因是B.A_access()
返回A
对象的副本,而不是包含您尝试使用的std::map
的实际A
对象
如果要使用包含要操作的std::map
的实际A
对象,则A\u访问
应返回对A
的引用,而不是A
的副本
因此,解决方案应该是:
A& A_access(){return a;}
std::map theMap.它不能被编译map需要两个模板参数。B.A_access()
在类C
中使用时返回A
对象的副本,该副本在执行It->first
之前就消失了。但即使我修改代码以返回这样的迭代器:(在类C中)It=B.A_access().theMap_access(to_access);和(在类A中)std::map::iterator theMap_access(){std::string to_access){it=theMap.find(to_access);返回它;}我面临着同样的问题。你知道我如何解决这个问题并指向C类的地图吗?谢谢。@Eglantine不,这与迭代器的设置无关。它与A\u access
返回的内容有关。你错误地处理了A
的副本,而这些副本在该行被删除后就会消失谢谢你,已经修好了!祝你今天愉快。