让我们尝试修复您的程序片段:
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);
}
等等...