[英]map/set iterator is not dereferencable C++ map
Please, have a look at my code. 请看看我的代码。
int main () {
Program* allcommand = new Program;
allcommand->addCommand("add", new Add);
allcommand->addCommand("convert", new Convert);
allcommand->addCommand("exit", new Exit);
allcommand->addCommand("help", new Help);
allcommand->addCommand("show", new Show);
allcommand->addCommand("modify", new Modify);
std::string input;
Command* obj;
while (true) {
std::cout << "\nCommand >> ";
std::getline(std::cin, input);
std::map<std::string, Command*> :: iterator it;
std::vector<std::string> parsedinput = allcommand->parse(input);
it = allcommand->getCommands().find(parsedinput[0]);
obj = it->second;
obj->start(parsedinput);
delete obj;
}
return 0;
}
It registers commands to a map which holds its command name and pointer to its class. 它将命令注册到包含其命令名称和指向其类的指针的映射中。 This compiles without problems but when I enter a command, it crashes with "map/set iterator not dereferencable".
编译没有问题,但是当我输入命令时,它崩溃,并显示“ map / set迭代器不可取消引用”。 I am new to maps (few minutes) so please help.
我是地图新手(几分钟),所以请帮忙。
EDIT. 编辑。 Ok I found that the problem is not in main... Here is code of Program class (some of it)
好吧,我发现问题不在主要...这是Program类的代码(其中一些)
void Program::addCommand(std::string command1, Command* obj) {
m_allCommands[command1] = obj;
}
std::map<std::string, Command*> Program::getCommands () {
return m_allCommands;
}
I think the problem is here, because after i register commands in main, I cannot cout the name of any command (same problem) 我认为问题出在这里,因为在main中注册命令后,我无法指出任何命令的名称(同样的问题)
std::map<std::string, Command*> Program::getCommands () {
return m_allCommands;
}
returns a copy of the m_allcommands
map. 返回
m_allcommands
映射的副本。 So when you do: 因此,当您这样做时:
it = allcommand->getCommands().find(parsedinput[0]);
You get an iterator on the temporary object returned by allcommand->getCommands()
that gets destroyed when the assignment is done. 您会在
allcommand->getCommands()
返回的临时对象上获得一个迭代器,该迭代器在分配完成后会被销毁。 Therefore it points to nothing. 因此,它什么都没有指向。
Change getCommands()
to: 将
getCommands()
更改为:
std::map<std::string, Command*>& Program::getCommands () {
return m_allCommands;
}
or even better: 甚至更好:
const std::map<std::string, Command*>& Program::getCommands () const {
return m_allCommands;
}
After a call to find()
you need to check if 调用
find()
您需要检查是否
if(it == allcommand->getCommands().end()) {
//Not Found
} else {
obj = it->second;
obj->start(parsedinput);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.