C ++ 11 regex_token_iterator

时间:2012-08-28 06:04:33

标签: c++ regex c++11 copy

嗯......我以为我理解正则表达式,我认为我理解迭代器,但是C ++ 11的正则表达式实现让我感到困惑......

我不明白的一个领域:阅读regex token iterators,我看到了以下示例代码:

#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"));
   ...
}

我不明白以下输出如何:

Quick
brown
fox.

由上面的std :: copy()函数创建。我看不到循环,所以我对迭代的发生方式感到困惑。或换句话说,如何生成多行输出?

1 个答案:

答案 0 :(得分:4)

std::copy将输入范围内的元素复制到输出范围。在您的程序中,输入范围是使用正则表达式分隔符提取的三个标记。这些是打印到输出的三个单词。输出范围是ostream_iterator,它只是获取给定的每个元素,并将元素写入输出流。

如果您使用调试器单步执行std::copy,您将看到它遍历输入范围的元素。