CS106L

Functions & Lambdas

0 points

Attendancefor this activity has closed. Sign in to be counted — nothing is recorded while you are signed out, and the activity itself works either way.

Let the Predicate Decide

find hardcodes *it == value. instead calls a predicate on each element.

In search.h, implement findIf so it returns the iterator to the first element for which pred(*it) is true. Return last if there is no match.

search.h · find-if · you write the boxed part
1#pragma once2 
Hint

Use a loop with ++it. Test pred(*it) rather than comparing an element with a fixed value.

main.cpp
1#include <iostream>2#include <vector>3#include "search.h"4 5bool isEven(int value) { return value % 2 == 0; }6 7int main() {8    std::vector<int> nums = {3, 7, 10, 12};9    auto result = findIf(nums.begin(), nums.end(), isEven);10    if (result != nums.end()) {11        std::cout << "First even: " << *result << "\n";12    } else {13        std::cout << "Not found\n";14    }15    auto absent = findIf(nums.begin(), nums.end(), [](int x) { return x < 0; });16    std::cout << "No negatives: " << std::boolalpha << (absent == nums.end()) << "\n";17}
$g++ -std=c++17 main.cpp -o main
press RUN to compile
0 of 1 done