To filter items of a vector based on a condition in C++, you can use the `std::remove_if` algorithm provided by the algorithm header in combination with the erase-remove idiom.
In this example,
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Define a vector containing elements
std::vector<int> vec = {1, 5, 10, 15, 20};
// Specify the threshold for filtering
int threshold = 10;
// Define a lambda function to filter elements greater than the threshold
auto condition = [threshold](int x) { return x > threshold; };
// Use std::remove_if algorithm with the condition
vec.erase(std::remove_if(vec.begin(), vec.end(), condition), vec.end());
// Print the filtered vector
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
15 20
In this example,
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Define a vector containing elements
std::vector<int> vec = {1, 5, 10, 15, 20};
// Specify the condition for filtering
auto condition = [](int x) { return x % 2 == 0; }; // Select even numbers
// Use std::remove_if algorithm with the condition
vec.erase(std::remove_if(vec.begin(), vec.end(), condition), vec.end());
// Print the filtered vector
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
1 5 15
In this tutorial, we learned How to Filter Items of a Vector based on a Condition in C++ language with well detailed examples.