(C++) Write a function named oddsEvens that takes in 3 integer vectors. The 1st
ID: 3572240 • Letter: #
Question
(C++) Write a function named oddsEvens that takes in 3 integer vectors. The 1st vector will contain some number of integers and the 2nd and 3rd vectors should be passed in empty. The function should fill the 2nd vector with all of the even values in the 1st vector and fill the 3rd vector with all of the odd values in the 1st vector. The first vector must remain unchanged.
For example, if the 1st vector passed in contains the values {6, 5, 2, 10, 11, 4}, then when the function returns, the 2nd vector passed in should contain the values {6, 2, 10, 4} (the even values) and the 3rd vector passed in should contain the values {5, 11} (the odd values).
The function should just return (do nothing) if either the 2nd or the 3rd vector are not passed in empty.
Give an example of the invocation of this function; you must show the declarations of any variables needed for this purpose, but you do not need to "populate" them - i.e. do not show where they are assigned values.
Explanation / Answer
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include <iostream>
#include <vector>
using namespace std;
void oddsEvens(vector<int>& from, vector<int>& even, vector<int>& odd) {
for(int n : from) { //iterate through each element in the from vector
if(n%2 ==0) //if the element is even
even.push_back(n); //add to even vector
else //if not even
odd.push_back(n); //add to odd vector
}
}
int main()
{
// Create a vector containing integers
std::vector<int> from = {6, 5, 2, 10, 11, 4};
std::vector<int> odd, even;
oddsEvens(from, even, odd);
cout << "Even vector elements: " << endl;
// Iterate and print values of even vector
for(int n : even) {
std::cout << n << ' ';
}
cout << "Odd vector elements: " << endl;
// Iterate and print values of odd vector
for(int n : odd) {
std::cout << n << ' ';
}
}
----------------------------------------------------------------------------
OUTPUT:
Even vector elements:
6
2
10
4
Odd vector elements:
5
11
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.