英文:
Why does changing the order of calling std::regex::str and std::regex::suffix change the behaviour?
问题
我已经编写了一些可以打印出每次连续出现两个元音字母的工作代码。
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();
}
但是当我像这样更改顺序时:
while (std::regex_search(t, r, x)) {
t = r.suffix();
std::cout << "match: " << r.str() << '\n';
}
它突然开始产生随机结果。我不明白这两行之间的关联,以及改变它们的顺序会影响什么。有人能解释一下吗?
英文:
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?
答案1
得分: 6
这个语句:
t = r.suffix();
并不会创建一个新的字符串对象,也不会改变字符串对象 t
所代表的内容,等等;相反,它是通过复制 r.suffix()
的内容来改变现有的字符串对象。
而 r
并不保存实际的字符串数据;它只保存索引信息,以便可以从 t
中提取适当的字符串数据。对 t
进行修改实际上会使旧的索引无效,因此会得到错误的字符串数据。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论