I want to Know that why this first block is right? And the second block is wrong?
vector<string_view> split(const string & str, char target) {
vector<string_view> res;
string_view s(str);
int pos = 0;
while (pos < s.size()) {
while (pos < s.size() && s[pos] == target) {
pos ;
}
int start = pos;
while (pos < s.size() && s[pos] != target) {
pos ;
}
if (pos > start) {
res.emplace_back(s.substr(start, pos - start));
}
}
return res;
}
vector<string_view> split(const string & str, char target) {
vector<string_view> res;
int pos = 0;
while (pos < str.size()) {
while (pos < str.size() && str[pos] == target) {
pos ;
}
int start = pos;
while (pos < str.size() && str[pos] != target) {
pos ;
}
if (pos > start) {
res.emplace_back(str.substr(start, pos - start));
}
}
return res;
}
The wrong answer when I input "Are You Okay": wrong answer
I don't know how is it.
CodePudding user response:
s.substr(start, pos - start)
s
is a std::string_view
. In this version, std::string_view::substr
returns a string_view
of a data that's owned by the underlying str
that gets passed in as a parameter to this function.
str.substr(start, pos - start)
str
is the original std::string
that gets passed in. In this version, calling substr()
on the original std::string
returns a new std::string
.
As part of evaluating this expression, a string_view
gets created on the string that belongs to the returned std::string
object.
The returned std::string
object is used temporarily, solely in this expression. Therefore, at the conclusion of the expression the std::string
that's returned from std::string::substr
gets automatically destroyed.
The string_view
on the string that belonged to the temporary std::string
object now becomes invalid, and all subsequent use of it results in undefined behavior.