CodeBlanks Logo Icon CodeBlanks

Search and filter

Write search and filtering with STL algorithms.

Search with STL

To search by title in the library we use the std::find_if algorithm. It finds the first element that matches a condition. The condition is given as a lambda expression: [&t](const Book& b) { return b.getTitle() == t; }.

A lambda is a small anonymous function. [&t] captures the outer variable t by reference. (const Book& b) is the parameter and { return b.getTitle() == t; } is the body. You will study lambda expressions in detail in the next group; for now this usage is enough. std::find_if returns an iterator; if it equals books.end() the element was not found.

searchByTitle method

The searchByTitle(const std::string& t) method uses std::find_if to search for a book whose title matches. If the returned iterator equals books.end() it returns false, otherwise true. The method is marked const because it does not modify the class.

We add this method to the previous lesson's Library class (the one with checkout). Do not forget #include <algorithm>; std::find_if lives in that header. Now the library supports both checkout and search; the next lesson combines them in a menu.

Practice Add the searchByTitle method

Take the previous lesson's classes and add #include <algorithm>. Add bool searchByTitle(const std::string& t) const to Library: use std::find_if over books.begin() and books.end() with the lambda [&t](const Book& b) { return b.getTitle() == t; }; return true if the iterator differs from books.end(). In main, search for "İnce Memed" and print "found" on success.

Starter code

main.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class Book {
private:
    std::string title;
    std::string author;
public:
    Book(std::string t, std::string a) : title(t), author(a) {}
    std::string getTitle() const { return title; }
    std::string getAuthor() const { return author; }
};

class Library {
private:
    std::vector<Book> books;
    std::vector<bool> borrowed;
public:
    void addBook(const Book& b) { books.push_back(b); borrowed.push_back(false); }
    size_t count() const { return books.size(); }
    Book getBook(int idx) const { return books[idx]; }
    bool checkout(int idx) {
        if (idx < 0 || idx >= (int)books.size()) return false;
        if (borrowed[idx]) return false;
        borrowed[idx] = true;
        return true;
    }
};

int main() {
    Library lib;
    lib.addBook(Book("Tutunamayanlar", "Oğuz Atay"));
    lib.addBook(Book("İnce Memed", "Yaşar Kemal"));
    // Search for "İnce Memed" and print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class Book {
private:
    std::string title;
    std::string author;
public:
    Book(std::string t, std::string a) : title(t), author(a) {}
    std::string getTitle() const { return title; }
    std::string getAuthor() const { return author; }
};

class Library {
private:
    std::vector<Book> books;
    std::vector<bool> borrowed;
public:
    void addBook(const Book& b) { books.push_back(b); borrowed.push_back(false); }
    size_t count() const { return books.size(); }
    Book getBook(int idx) const { return books[idx]; }
    bool checkout(int idx) {
        if (idx < 0 || idx >= (int)books.size()) return false;
        if (borrowed[idx]) return false;
        borrowed[idx] = true;
        return true;
    }
    bool searchByTitle(const std::string& t) const {
        auto it = std::find_if(books.begin(), books.end(),
            [&t](const Book& b) { return b.getTitle() == t; });
        return it != books.end();
    }
};

int main() {
    Library lib;
    lib.addBook(Book("Tutunamayanlar", "Oğuz Atay"));
    lib.addBook(Book("İnce Memed", "Yaşar Kemal"));
    if (lib.searchByTitle("İnce Memed")) {
        std::cout << "found";
    }
    return 0;
}

Expected output

found

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which STL algorithm searches by condition?

main.cpp
// finds the first match by condition
  • std::sort
  • std::find_if Correct answer
  • std::count
  • std::transform

Explanation: std::find_if finds the first element matching a condition.

2 Complete the find_if call

Question
auto it = std::____(books.begin(), books.end(), [&t](const Book& b) { return b.getTitle() == t; });
Answer
auto it = std::find_if(books.begin(), books.end(), [&t](const Book& b) { return b.getTitle() == t; });

Explanation: std::find_if finds the first element matching a condition.

3 Match each piece to its role

Term Meaning
std::find_if Searches by condition
books.begin() Range start
books.end() Range end
[&t](const Book& b) Lambda capture

All lessons in Intermediate