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

2020-07-16 10:04:29
在查詢序列的子序列方面,search() 演算法和 find_end() 演算法相似,但它所查詢的是第一個匹配項而不是最後一個。

和 find_end() 演算法一樣,它也有兩個版本,第二個版本接受用來比較元素的謂詞作為第 5 個引數。可以用 search() 來驗證前面使用 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"};
size_t count {};
auto iter = std::begin(text);
auto end_iter = end(text);
while((iter = std::search(iter, end_iter, std::begin(phrase), std::end (phrase) , [](char ch1, char ch2) { return std::toupper (ch1) == std:: toupper (ch2); })) != end_iter)
{
    ++count;
    std::advance(iter, phrase.size()); // Move to beyond end of subsequence found
}
std::cout << "n""<< phrase << "" was found "<< count << " times." << std::endl;
這段程式碼執行後會輸出下面的內容:

Smith, where Jones had had "had", had had "had had". "Had had" had had the examiners' approval.
"had had" was found 5 times.

我們仍然忽略大小寫來搜尋“had had”,但會正向查詢第一個匹配項。search() 演算法返回的疊代器指向找到的子序列的第一個元素,因此為了搜尋 phrase 的第二個範例,iter 必須增加 phrase 中元素的個數,使它指向下一個找到的序列的第一個元素。