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