Question: I am writing a c++ program that uses the replace_if to replace all even numbers with the number 0 . Is there any way to

I am writing a c++ program that uses the replace_if to replace all even numbers with the number 0

.

Is there any way to write the functor class from algorithm_utils.h and algorithm_utils..cpp so the functor of the main.cpp will output this result?:

1: changed 2 to 0

2: changed 4 to 0

3: changed 6 to 0

4: changed 8 to 0

5: changed 10 to 0

6: changed 12 to 0

7: changed 14 to 0

8: changed 16 to 0

9: changed 18 to 0

10: changed 20 to 0

vectorOfInts now contains: 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15 0 17 0 19 0

--mycode--

--main.cpp--

#include "algorithm_utils.h" #include #include #include #include #include

using namespace std;

int main () { std::vector vectorOfInts;

// set some values: for (int i=1; i<=20; i++) vectorOfInts.push_back(i);

// TODO: use replace_if to replace all even numbers with 0 std::replace_if (vectorOfInts.begin(), vectorOfInts.end(), IsEven, 0);

std::cout << "vectorOfInts now contains:"; for (std::vector::iterator it=vectorOfInts.begin(); it!=vectorOfInts.end(); ++it) std::cout << ' ' << *it; std::cout << ' ';

std::vector vectorOfInts2; for (int i=1; i<=20; i++) vectorOfInts2.push_back(i);

// TODO: use replace_if to replace all even numbers with 0 using a function object or functor // The functor needs to do the ouptut of each replaced element.

std::replace_if (vectorOfInts.begin(), vectorOfInts.end(), IsEven, 0);

std::cout << "vectorOfInts now contains:"; for (std::vector::iterator it=vectorOfInts2.begin(); it!=vectorOfInts2.end(); ++it) std::cout << ' ' << *it; std::cout << ' '; return 0; }

--algorithm_utils.h--

#ifndef LESSON_9_STL_ALGORITHM_REPLACE_IF_ALGORITHM_UTILS_H #define LESSON_9_STL_ALGORITHM_REPLACE_IF_ALGORITHM_UTILS_H

#include

// TODO: put the prototype of the function to test for even here bool IsEven (int i);

// TODO: put the declaration of the functor class that tests for even values here

#endif

--algorithm_utils.cpp--

#include "algorithm_utils.h"

// TODO: put the definition of the function to test for even here bool IsEven (int i){ return ((i%2)==0); }

// TODO: put the definitions for the functor here

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!