2012-08-28 42 views
5

嗯...我想我的理解正則表達式,我想我明白迭代器,但C++ 11的正則表達式實施,我不解......C++ 11 regex_token_iterator

的一個領域,我不明白:閱讀有關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. 

正被性病::複製()創建函數的以上。我看不到任何循環,所以我對迭代的發生感到困惑。換句話說,如何產生多於一行的輸出?

+0

它將每一個複製到輸出。循環在'copy'裏面。 – chris

回答

4

std::copy將來自輸入範圍的元素複製到輸出範圍中。在您的程序中,輸入範圍是使用正則表達式分隔符提取的三個令牌。這些是打印到輸出的三個單詞。輸出範圍是ostream_iterator,它簡單地獲取給定的每個元素並將元素寫入輸出流。

如果您使用調試器步進通過std::copy,您會看到它在輸入範圍的元素上循環。

+0

啊 - 我沒有想過嘗試 - 我認爲std :: copy()是從開始迭代器到結束迭代器的簡單字節級副本。 謝謝,詹姆斯。 – U007D

+0

不可以,'std :: copy'是標準庫算法之一(通常稱爲_STL_的一部分),它和其他算法一樣對元素範圍進行操作。在這種情況下,元素就是令牌。 –

+0

現在是完美的感覺。 – U007D