让我们来尝试修复你的程序片断:
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);
}
等等......
嗯,你在外面访问矢量的范围。 – juanchopanza
错误发生时'content [i]'的值是多少? – Barmar
@juanchopanza错误在'substr'中,而不是矢量访问器。 – Barmar