-10

运行时出现此错误:

在抛出 'std::out_of_range' what(): basic_string::substr 的实例后调用终止

问题出在这部分代码中,但我是全新的,我不明白应该如何解决这个问题。内容是我的字符串向量。

    int i=1;
    std::string v1, v2, weight;
    while(!content.empty())
    {
        v1 = content[i].substr(2,1);
        v2 = content[i].substr(5,1);
        weight = content[i].substr(8,1);
        i++;
    }
4

2 回答 2

3

这里有两个主要问题。

您的循环将永远持续下去(或者直到您从无效访问中杀死您的 RAM 棒),因为您只检查向量是否为空,而不是检查是否i已达到其总大小。

for (auto& x : content) {
    const std::string v1     = x.substr(2,1);
    const std::string v2     = x.substr(5,1);
    const std::string weight = x.substr(8,1);

    // Presumably actually do something with these now
}

然后您需要修复您的substr操作,这些操作具有错误的参数并因此导致异常。

于 2014-04-10T21:00:22.217 回答
2

让我们尝试修复您的程序片段:

int i=1;
std::string v1, v2, weight;
while( i < content.size() && content[i].size() >= 8 )
{
    v1 = content[i].substr(2,1);
    v2 = content[i].substr(5,1);
    weight = content[i].substr(8,1);
    i++;
}

那是最小的修复。我本来希望:

std::string v1, v2, weight;
content.erase(content.begin());
for( const auto& x: content )
{
    if( x.size() < 8 )
         continue; // or break, whatever is best

    v1 = x.substr(2,1);
    v2 = x.substr(5,1);
    weight = x.substr(8,1);
}

您还可以改变对待较短物品的方式:

inline int guarded_substr(const std::string& s, std::size_t begin, size_t size) {
    return s.size() >= begin+size ? s.substr(begin, size) : std::string();
}

std::string v1, v2, weight;
content.erase(content.begin());
for( const auto& x: content )
{
    v1 = guarded_substr(x,2,1);
    v2 = guarded_substr(x,5,1);
    weight = guarded_substr(x,8,1);
}

等等...

于 2014-04-10T21:37:00.390 回答