std::vector<double> values {2.7, 2.7, 2.7, 3.14, 3.14, 3.14, 2.7, 2.7}; double value {3.14}; int times {3}; auto iter = std::search_n(std::begin(values), std::end(values), times, value); if (iter != std::end(values)) std::cout << times << " successive instances of " << value<< " found starting index " << std::distance (std::begin (values), iter) <<std::endl;這段程式碼會在 values 容器中查詢第一個有 3 個 value 範例的匹配項。它找到的序列的索引為 3。注意用來指定個數的第三個引數必須是無符號整型;如果不是,編譯這段程式碼會產生警告。
// Searching using search_n() to find freezing months #include <iostream> // For standard streams #include <vector> // For vector container #include <algorithm> // For search_n() #include <string> // For string class using std::string; int main() { std::vector<int> temperatures {65, 75, 56, 48, 31, 28, 32, 29, 40, 41, 44, 50}; int max_temp {32}; int times {3}; auto iter = std::search_n(std::begin(temperatures), std::end(temperatures), times, max_temp,[](double v, double max){return v <= max; }); std::vector<string> months {"January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"}; if(iter != std::end(temperatures)) std::cout << "It was " << max_temp << " degrees or below for " << times<< " months starting in " << months[std::distance(std::begin(temperatures), iter)]<< std::endl; }temperatures 容器中儲存了一年中每個月份的平均溫度。search_n() 的最後一個引數是一個 lambda 表示式的謂詞,當元素小於等於 max_temp 時,它會返回 true。month 容器中儲存月份的名稱。
It was 32 degrees or below for 3 months starting in May