In this C++ tutorial, you shall learn how to filter even numbers in a vector using a For loop and vector::push_back() function, with example programs.
Filter even numbers in integer Vector in C++
To filter even numbers in an integer vector in C++, iterate over the elements of the vector, check if each element is even number or not, and if the element is even number, add it to the resulting vector.
The code to filter even numbers in vector v1
to a resulting vector result
is
for ( auto& n : v1 ) {
if ( n % 2 == 0 ) {
result.push_back(n);
}
}
C++ Program
In the following program, we take an integer vector in v1
and filter the even numbers in this vector to result
vector.
We will use Foreach loop statement to iterate over the elements of the vector v1
, If statement to check if the element is even number, Modulus Operator to find the remainder when element is divided by 2, and Equal-to comparison operator to check if remainder equals zero.
main.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
//int vector
vector<int> v1 { 1, 2, 4, 7, 8, 10, 13 };
//filter even numbers of v1
vector<int> result {};
for ( auto& n : v1 ) {
if ( n % 2 == 0 ) {
result.push_back(n);
}
}
//print result vector
for ( auto& n : result ) {
cout << n << " ";
}
}
Output
2 4 8 10
Conclusion
In this C++ Tutorial, we learned how to filter even numbers from given vector.