C++ adjacent_find(STL adjacent_find)演算法使用詳解

2020-07-16 10:04:30
adjacent_find() 演算法可以用來搜尋序列中兩個連續相等的元素。用 == 運算子來比較連續的一對元素,返回的疊代器指向前兩個相等元素中的第一個。如果沒有一對相等的元素,這個演算法返回這個序列的結束疊代器。例如:
string saying {"Children should be seen and not heard."};
auto iter = std::adjacent_find(std::begin(saying), std::end(saying));
if (iter != std::end(saying))
    std::cout <<"In the following text: n""<< saying << ""n'"<< *iter << "' is repeated starting at index position "<< std::distance(std::begin(saying), iter) << std::endl;
這裡會搜尋 saying 字串的前兩個相等字元,所以這段程式碼的輸出如下:

In the following text:
"Children should be seen and not heard."
'e' is repeated starting at index position 20

adjacent_find() 演算法的第二個版本,允許我們提供一個應用於連續元素的謂詞。下面展示了如何用這個函數來查詢這個序列中第一對都為奇數的連續整數:
std::vector<long> numbers {64L, 46L, -65L, -128L, 121L, l7L, 35L, 9L, 91L, 5L};
auto iter = std::adjacent_find(std::begin(numbers),std::end(numbers),[](long n1, long n2){ return n1 % 2 && n2 % 2; });
if(iter != std::end(numbers))
    std::cout <<"The first pair of odd numbers is "<< *iter << " and " << *(iter+1) << std::endl;
當兩個引數都不能被 2 整除時,這個 lambda 表示式就返回 true,所以這段程式碼會找到 121 和 17。