Menu
Coddy logo textTech

Vector Data Filtering

Part of the Logic & Flow section of Coddy's C++ journey. Lesson 54 of 56.

challenge icon

Challenge

Easy

Create a program that implements a data filtering system to extract specific numbers from a collection. This challenge will test your ability to combine vectors, iteration, conditional logic, and function design to process data selectively.

The following inputs will be provided:

  • An integer n representing the number of integers in the collection
  • Then n integers representing the numbers to be filtered
  • An integer threshold representing the minimum value for filtering

Your program should:

  1. Create a function named filterNumbers that takes a std::vector<int> and an integer threshold as parameters
  2. The function should return a new std::vector<int> containing only the numbers from the original vector that are greater than the threshold
  3. In the main function, read the input values and populate a vector with the n integers
  4. Call the filterNumbers function with the populated vector and threshold
  5. Print the count of filtered numbers first, then print each filtered number on a separate line

Use the following exact output format:

First line - count of filtered numbers:

Filtered count: [number_of_filtered_elements]

Then each filtered number on separate lines:

[filtered_number_1]
[filtered_number_2]
...

If no numbers pass the filter, only print:

Filtered count: 0

Remember that your filterNumbers function should create a new empty vector, iterate through the input vector using a range-based for loop, and use an if-statement to check each number against the threshold. Only numbers that are strictly greater than the threshold should be added to the result vector using push_back(). The function should return the new vector containing only the filtered elements.

Try it yourself

#include <iostream>
#include <vector>
using namespace std;

// TODO: Create the filterNumbers function here

int main() {
    // Read the number of integers
    int n;
    cin >> n;
    
    // Read the integers into a vector
    vector<int> numbers;
    for (int i = 0; i < n; i++) {
        int num;
        cin >> num;
        numbers.push_back(num);
    }
    
    // Read the threshold
    int threshold;
    cin >> threshold;
    
    // TODO: Call the filterNumbers function and store the result
    
    // TODO: Print the filtered count and numbers according to the required format
    
    return 0;
}

All lessons in Logic & Flow

Practice on your own: Online C++ compiler