简体   繁体   English

C ++ 11 regex_token_iterator

[英]C++11 regex_token_iterator

Hmm... I thought I understood regexes, and I thought I understood iterators, but C++11's regex implementation has me puzzled... 嗯......我以为我理解正则表达式,我认为我理解迭代器,但C ++ 11的正则表达式实现让我感到困惑......

One area I don't understand: Reading about regex token iterators , I came across the following sample code: 我不明白的一个领域:阅读有关正则表达式令牌迭代器的内容 ,我遇到了以下示例代码:

#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <regex>
int main()
{
   std::string text = "Quick brown fox.";
   // tokenization (non-matched fragments)
   // Note that regex is matched only two times: when the third value is obtained
   // the iterator is a suffix iterator.
   std::regex ws_re("\\s+"); // whitespace
   std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1),
              std::sregex_token_iterator(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
   ...
}

I don't understand how the following output: 我不明白以下输出如何:

Quick
brown
fox.

is being created by the std::copy() function above. 正在由上面的std :: copy()函数创建。 I see no loop, so I am puzzled as how the iteration is occurring. 我看不到循环,所以我对迭代的发生方式感到困惑。 Or put another way, how is more than one line of output being generated? 换句话说,如何生成多行输出?

std::copy copies elements from an input range into an output range. std::copy将输入范围内的元素std::copy到输出范围。 In your program, the input range is the three tokens extracted using the regular expression delimiter. 在您的程序中,输入范围是使用正则表达式分隔符提取的三个标记。 These are the three words that are printed to the output. 这些是打印到输出的三个单词。 The output range is ostream_iterator which simply takes each element it is given and writes the element to an output stream. 输出范围是ostream_iterator ,它简单地获取给定的每个元素,并将元素写入输出流。

If you step through std::copy using your debugger, you will see that it loops over the elements of the input range. 如果您使用调试器单步执行std::copy ,您将看到它循环输入范围的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM