改变调用 std::regex::str 和 std::regex::suffix 的顺序为何会改变行为?

huangapple go评论55阅读模式
英文:

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(&quot;(a|e|i|o|u){2}&quot;);

std::smatch r;

std::string t = some_string;

while (std::regex_search(t, r, x)) {
    std::cout &lt;&lt; &quot;match: &quot; &lt;&lt; r.str() &lt;&lt; &#39;\n&#39;;

    t = r.suffix();
}

But when I change the order like this:

while (std::regex_search(t, r, x)) {
    t = r.suffix();

    std::cout &lt;&lt; &quot;match: &quot; &lt;&lt; r.str() &lt;&lt; &#39;\n&#39;;
}

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.

huangapple
  • 本文由 发表于 2023年3月1日 15:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定