在C++中使用字符串迭代器的无限循环

Ole*_*ade 0 c++ iterator infinite-loop

虽然我愿意解析字符串中包含的指令,但我基本上是试图从它的空格和制表符字符中清除字符串,以便在其中查找指令.不幸的是,我的循环进入一个无限循环,我无法找到为什么因为我在每次擦除char时刷新迭代器...

请帮忙吗?

void  myClass::parseInstructions(std::string& line)
{
    std::string::iterator        it;

    for (it = line.begin(); it != line.end(); ++it)
        if (((*it) == ' ') || ((*it) == '\t'))
            it = line.erase(it);
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 12

您的代码流程:

it = line.begin(); 
while (it != line.end()) {
    if (((*it) == ' ') || ((*it) == '\t'))
        it = line.erase(it);
    ++it;
}
Run Code Online (Sandbox Code Playgroud)

正确的代码:

it = line.begin(); 
while (it != line.end()) {
    if (((*it) == ' ') || ((*it) == '\t'))
        it = line.erase(it);
    else // <---- THIS IS IMPORTANT
        ++it;
}
Run Code Online (Sandbox Code Playgroud)

现在你会连续错过两个空白字符,当最后一个字符是空白时,你会移动到最后.

或者你可以使用std::remove_copy_if,它应该具有低得多的复杂性.