Vector Data Filtering
Part of the Logic & Flow section of Coddy's C++ journey. Lesson 54 of 56.
Challenge
EasyCreate 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
nrepresenting the number of integers in the collection - Then
nintegers representing the numbers to be filtered - An integer
thresholdrepresenting the minimum value for filtering
Your program should:
- Create a function named
filterNumbersthat takes astd::vector<int>and an integer threshold as parameters - The function should return a new
std::vector<int>containing only the numbers from the original vector that are greater than the threshold - In the main function, read the input values and populate a vector with the
nintegers - Call the
filterNumbersfunction with the populated vector and threshold - 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: 0Remember 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
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating ItemsPractice on your own: Online C++ compiler