讓我們來嘗試修復你的程序片斷:
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