Question #76528

Write a function remove_odd that takes in a set of integers and removes all the odd elements.

Hint: you will need to use an iterator to iterate through the elements in a set.

Hint: In C++11, an auto keyword can be use to automatically infer the type. e.g. autoiter = s.begin()

#include <set>

using namespace std;

void remove_odd(set<int> s) {
//code
}

Expert's answer

#include <iostream>
#include <set>
//#include <iterator>

using namespace std;

// function removes all the odd elements
void remove_odd(set<int> &s) {
for (set<int>::iterator it=s.begin(); it!=s.end();) {
if (*it%2==1)
s.erase(it++);
else ++it;
}
}


// print set
void print (const set<int> &s) {
for (set<int>::iterator it=s.begin(); it!=s.end(); ++it)
cout << *it << " ";
cout << endl;
}

main() {
set<int> a = {1,2,4,5,6,7,9,10};

print(a);
remove_odd(a);
print(a);

return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS