Menu
CoddyTech

Iterators and Closures

Lesson 22 of 48 in Coddy's Rust for C++ Developers course.

C++ algorithms take iterators and callable objects; lambdas choose captures such as by value or by reference. Rust iterator adaptors often defer work until a consuming operation requests elements. A Rust closure infers how it borrows or moves captured values from its body; move forces capture by value but does not by itself mean each call consumes those captures. A closure that updates a captured counter needs mutable access to its environment and implements the appropriate callable trait. any is a short-circuiting consumer: it stops once the predicate succeeds. The source vector can remain owned by the caller when iterated through shared references. Trace the number of predicate invocations separately from the collection length; they need not be equal.

Complete standalone C++17 program:

#include <algorithm>
#include <iostream>
#include <vector>
int main() {
    std::vector<int> values{1, 6, 8};
    int visited = 0;
    bool found = std::any_of(values.begin(), values.end(), [&](int n) {
        ++visited; return n > 4;
    });
    std::cout << std::boolalpha << found << ' ' << visited << '\n';
}

Complete standalone Rust program:

fn main() {
    let values = vec![2, 9, 12];
    let limit = 5;
    let mut visited = 0;
    let found = values.iter().any(|&value| { visited += 1; value > limit });
    println!("{} {}", if found { 1 } else { 0 }, visited);
}
challenge icon

Challenge

Easy

Implement pub fn excess(values: &[i32], floor: i32) -> Vec<i32> in pipeline.rs. Preserve order, select values strictly greater than floor, and return each selected value minus the floor. Do not change the input. Input is a floor followed by zero or more integers, all from -1000 to 1000. solve returns comma-separated results or empty when none remain. Implement the transformation through the public API; it must work for subslices, empty slices and repeated calls with different floors.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, pipeline.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod pipeline;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let values = vec![17, -4, 8, 8, 3];
assert_eq!(pipeline::excess(&values[1..], 3), vec![5, 5]);
assert_eq!(pipeline::excess(&values[1..], -4), vec![12, 12, 7]);
assert_eq!(pipeline::excess(&[], 9), Vec::<i32>::new());
assert_eq!(pipeline::excess(&[4, 4], 4), Vec::<i32>::new());
assert_eq!(values, vec![17, -4, 8, 8, 3]);

    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for C++ Developers

Practice on your own: Online Rust compiler