Difference between these two codes
So I'm following my C++ textbook and its asking me why the top one doesn't work but the bottom does. I see that string s is defined outside in one, and inside of the while loop in the other. When running the first one, I get an error
dealing with allocation size. These two codes are only portions of the original code, but the only difference is where string s is defined. I don't see why the top one doesn't work though. Can someone help me explain?
"bordered" and "words" are two vectors of strings.
"maxlen" is the length of the longest word in "words"
Code:
vector<string> ret;
string::size_type width1 = maxlen + 1;
vector<string>::size_type i = 0, j = 0;
string s;
while (i != words.size() || j != bordered.size()){
if(i != words.size()){
s = words[i++];
}
s += string(width1 - s.size(), ' ');
if (j != bordered.size()){
s += bordered[j++];
}
ret.push_back(s);
}
and
Code:
vector<string> ret;
string::size_type width1 = maxlen + 1;
vector<string>::size_type i = 0, j = 0;
while (i != words.size() || j != bordered.size()){
string s;
if(i != words.size()){
s = words[i++];
}
s += string(width1 - s.size(), ' ');
if (j != bordered.size()){
s += bordered[j++];
}
ret.push_back(s);
}