C++ find_end(STL find_end)演算法詳解

2020-07-16 10:04:29
find_end() 會在一個序列中查詢最後一個和另一個元素段匹配的匹配項,也可以看作在一個元素序列中查詢子序列的最後一個匹配項。這個演算法會返回一個指向子序列的最後一個匹配項的第一個元素的疊代器,或是一個指向這個序列的結束疊代器。下面是一個範例:
string text {"Smith, where Jones had had "had", had had "had had"." " "Had had" had had the examiners' approval."};
std::cout << text << std::endl;
string phrase {"had had"};
auto iter = std::find_end(std::begin(text), std::end(text), std::begin (phrase),std::end(phrase));
if(iter != std::end(text))
std::cout << "The last "" << phrase<< "" was found at index "<< std::distance (std::begin (text), iter) << std::endl;
這段程式碼會從 text 中搜尋“had had”的最後一個匹配項,並輸出如下內容:

Smith, where Jones had had "had", had had "had had" . "Had had" had had the examiners' approval.
The last "had had" was found at index 63

可以在 text 中搜尋 phrase 的所有匹配項。在這個範例中只會記錄匹配項的個數:
size_t count {};
auto iter = std::end(text);
auto end_iter = iter;
while((iter = std::find_end(std::begin(text), end_iter, std::begin(phrase), std::end(phrase))) != end_iter)
{
    ++count;
    end_iter = iter;
}
std::cout << "n""<< phrase << "" was found " << count <<" times." << std::endl;
這個 while 迴圈表示式會進行這項搜尋工作。迴圈表示式會在 [std::begin(text),end_iter) 這個範圍內搜尋 phrase。最開始的搜尋範圍包含 text 中的全部元素。為了說明這裡發生了什麼,下面用圖 1 來演示這個過程。


圖 1 用 find_end() 反復搜尋