int N;
cin >> N;
for (int i = 0; i < N; i++)
{
//here string is redefined per loop cycle, still no error
string str;
cin >> str;
//ignore code below
for (int j = 0; j < str.length(); j++)
{
if (j % 2 == 0)
cout << str[j];
}
cout << " ";
for (int j = 0; j < str.length(); j++)
{
if (j % 2 != 0)
{
cout << str[j];
}
}
cout << endl;
}
return 0;
It sounds like you're asking why this (cut down version) is valid:
for (int i = 0; i < N; i++) {
string str;
}
when the string is being redefined every time through the loop.
However, that's perfectly acceptable. The lifetime of the string object extends from immediately after the semicolon following str
to the closing brace }
, which is part of the loop itself. Hence it effectively comes into, and goes out of, existence for every single iteration of that loop (a) .
It's no different really to the snippet:
{
int xyzzy = 42; // xyzzy now exists.
} // and no longer exists from here on.
(a) Technically, using the as-if rule, it could reuse the same object, provided it was cleared out to an empty string each time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.