Even-Odd sorting
Hello.
It seems a year is all it takes for one's proficiency in C++ to become
too rusty. Professionally, I've been away from the language (and from
programming in general), but I still preserve an appreciation for it.
So I decided to toy with some idea, just for fun and for evaluating how
rusty I'd become. "Let me write a simple functor for sorting the
elements of a collection! I will start with a simple collection of
integers.", I thought. I then chose an unusual criterion for the
sorting: "I'd like the elements to be ordered so that the even members
should appear before the odd ones." The following is what I came up
with. The program is not producing the expected behavior and I suspect
it has to do with my predicate. It is probably not fully complying to
the requirements for such a function.
#include <iostream>
#include <set>
#include <functional>
#include <algorithm>
#include <iterator>
class EvenOddSorting {
public:
bool operator()(const int i, const int j) const {
return i % 2 == 0 && j % 2 != 0;
}
};
int main() {
std::set<int, EvenOddSorting> intSet;
intSet.insert(10);
intSet.insert(7);
intSet.insert(5);
intSet.insert(18);
intSet.insert(3);
std::cout << "Even-Odd ordered set: ";
std::copy(intSet.begin(),
intSet.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
Given the above program, the expected output should read:
Even-Odd ordered set: 10 18 3 5 7
Notice how my proposed output implies a hidden requirement of ordering
among even and odd numbers. That would be ideal, but I'd be satisfied
(at first) with an output like '18 10 5 7 3'. Would anybody care to give
me a hand?
Thank you!
--
Ney Andr? de Mello Zunino