Conditional Functions in C++

Lesson Introduction

Welcome! Today, let's explore conditional functions in C++. Conditional functions help us decide and filter data based on conditions, making our code modular and easier to manage.

By the end, you’ll understand how to use std::count_if, std::copy_if, and std::replace_if with predicates in C++. Let’s start by understanding predicates.

Understanding Predicates

A predicate is a function that returns a boolean value, deciding whether a condition holds true.

Consider this function, is_even, which checks if a number is even:

bool is_even(int n) {
    return n % 2 == 0;
}

Here, the function returns true if n is even and false otherwise. This predicate will help us filter or count even numbers in our data. We can also define this predicate as lambda. We will use both versions.

Using `std::count_if`

std::count_if counts elements in a range that meet a condition, which is useful for knowing how many elements fit a criterion.

Here's how to count even numbers in a vector using std::count_if and is_even:

#include <iostream>
#include <vector>
#include <algorithm>

bool is_even(int n) {
    return n % 2 == 0;
}

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5, 6};
    
    // Count even numbers
    int count = std::count_if(data.begin(), data.end(), is_even);
    std::cout << "Number of even numbers: " << count << '\n';  // Number of even numbers: 3

    return 0;
}

std::count_if goes through data and counts elements that are even.

Using `std::copy_if`

std::copy_if copies elements from a source to a destination if they meet a condition. It’s useful for creating a new container with specific elements.

Here's how to copy even numbers from data to a new vector, evens:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

bool is_even(int n) {
    return n % 2 == 0;
}

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5, 6};
    std::vector<int> evens;
    
    // Copy even numbers to 'evens'
    std::copy_if(data.begin(), data.end(), std::back_inserter(evens), is_even);
    
    std::cout << "Even numbers: ";
    for (int n : evens) {
        std::cout << n << ' ';
    }
    std::cout << '\n';

    // Output: Even numbers: 2 4 6 
    
    return 0;
}

std::copy_if goes through data and copies even numbers to evens. std::back_inserter constructs a special iterator that appends elements to the end of evens as they are copied by std::copy_if.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal