I've written some working code that prints out every occurrence of 2 vowels in a row.
std::regex x("(a|e|i|o|u){2}");
std::smatch r;
std::string t = some_string;
while (std::regex_search(t, r, x)) {
std::cout << "match: " << r.str() << '\n';
t = r.suffix();
}
But when I change the order like this:
while (std::regex_search(t, r, x)) {
t = r.suffix();
std::cout << "match: " << r.str() << '\n';
}
it suddenly starts giving random results. I don't see the connection between these 2 lines, and why changing their order would affect anything. Can anyone explain this?
This statement:
t = r.suffix();
isn't creating a new string object, or changing what string object t denotes, or anything like that; rather, it's mutating the existing string object by copying over the contents of r.suffix().
And r doesn't hold the actual string data; it just holds index information so that the appropriate string data can be extracted from t. Mutating t essentially invalidates the old indices, so you get the wrong string data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With