[英]sregex_iterator next and end.. How does this work?
伙計們,我是 C++ 的新手。 所以請原諒我在這里的無知。 我試圖理解我上網的以下代碼。 while (next?= end) 行到底做了什么。 當我打印 &next 和 &end 的地址時,它們總是不同的(甚至發布 while 循環)。 我下一個 std std::sregex_iterator next
和std::sregex_iterator end
是兩個不同的實例。 那么,為什么while (next != end)
行認為它們在某個時間點會相等? 我看着引擎蓋下。 它似乎是regex_iterator<string::const_iterator>
。
我試圖了解構造函數等,但不想列出我發現的所有內容,因為它們可能不相關。 只是想讓您知道我來自 Java 世界,但一直在學習了解 C++ 的課程。
任何幫助深表感謝。 謝謝
string subject("This is a test");
try {
std::regex re("\\S+");
std::sregex_iterator next(subject.begin(), subject.end(), re);
std::sregex_iterator end;
while (next != end) {
std::smatch match = *next;
std::cout << match.str() << "\n";
std::cout << match.position() << "\n";
next++;
}
} catch (std::regex_error& e) {
// Syntax error in the regular expression
}
只是想讓你知道我來自 Java 世界,但一直在學習了解 C++ 的課程
這似乎是你困惑的原因。 與 Java 相比,C++ 使用值語義。 這意味着,當您通過==
比較兩個 object 時,它不會測試身份,而是測試相等性,即比較值。
考慮這個
int x = 42;
int y = 42;
那是兩個不同的對象,但它們的值是相同的:
assert( x == y );
assert( &x != &y );
Java 有這種盒裝和簡單類型的怪癖(不確定它們實際上是如何調用的),但在 C++ 中,也可以重載==
的自定義類型預計使用值語義。 例如
std::string x{"Foo"};
std::string y{"Foo"};
assert( x == y );
assert( &x != &y );
輸入迭代器通常事先不知道輸入在哪里結束。 例如,對於std::istream_iterator
也是如此。 在這種情況下啟用next != end
的一種可能方法是operator++
設置一些內部 state 以指示已到達輸入結束。 然后next != end
,只檢查是否在next
中設置了該標志(當然也需要end
,即默認構造的迭代器是“特殊的”,盡管這是實現細節,基本上你只需要知道它有效;) .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.