字符串迭代器不可解引用

string iterator is not dereferencable

本文关键字:引用 不可解 迭代器 字符串      更新时间:2023-10-16

我正在使用库来解析.pgn文件,当我试图运行项目时,我发现了这个错误:调试断言失败!文件:C: program files (x86)microsoft visual studio 11.0vcincludexstring .dll线:79不可解引用的字符串迭代器有关程序如何导致断言失败的信息,请参阅关于断言的visual c++文档。

问题是,当迭代器到达文件的末尾时,它指向什么(start iterator (itr1) == end iterator (itr2)),我试图添加条件来检查itr1是否到达文件的末尾,但它是无用的。所以请告诉我我的错在哪里。下面是我的源代码。cpp文件:

#include <iostream>
#include <fstream>
#include <PGNGameCollection.h>
int main()
{
    std::ifstream pgnfile("sample.pgn");
    pgn::GameCollection games;
    pgnfile >> games;
    std::cout << "the file sample.pgn contains " << games.size() << "games"     << std::endl;
    system("pause");
    return 0;
}

,下面是导致错误的类函数:

bool pgn::Parser::getComment(std::string::const_iterator &itr1, const std::string::const_iterator &itr2, pgn::CommentText &out)
{
    std::string::const_iterator local_itr=itr1;
    std::string comment;
    if(*local_itr != '{')
        return false;
    local_itr++; //skipping '{'
    while((*local_itr != '}') && (local_itr != itr2))
    {
        comment += *local_itr++;
    }
    local_itr++; //skipping '}'
    skipBlanks(local_itr, itr2);
    itr1=local_itr;
    out=pgn::CommentText(comment);
    return true;
}

skipBlanks功能:

void pgn::Parser::skipBlanks(std::string::const_iterator &itr1, cost std::string::const_iterator &end)
{
    while((itr1 != end) && (isspace(*itr1)))
    {
        itr1++;
    }
}

我已经搜索了stackoverflow和谷歌所有类似的问题,但我找不到答案。我还逐行跟踪代码,直到找到导致错误的函数。

如果itr2是你的end-iterator,那么在试图解引用它之前,你必须检查你的迭代器的end-condition

while((local_itr != itr2) && (*local_itr != '}'))

你在反其道而行,这肯定会导致你所描述的问题。

在函数的最开始添加end-condition检查也可能是有意义的,因为在那里您也解引用了local_itr

同样,如果你的循环因为local_itr到达itr2而终止,并且在itr2和之后没有任何东西,那么循环后的代码就没有意义。在这种情况下,不允许增加local_itr