C.Chew C.Chew - 2 months ago 7
C++ Question

What values are inserted in the set with this C++ code?

I was recently given an interview question that had the following code. Unfortunately, I didn't get it right. Could someone help explain what the code is doing, especially the commented line?

Here is the code.

#include <iostream>
#include <set>

struct C
{
bool operator()(const int &a, const int &b) const
{
return a % 10 < b % 10;
}
};

int main()
{
std::set<int> x({ 4, 2, 7, 11, 12, 14, 17, 2 });
std::cout << x.size();
std::set<int, C> y(x.begin(), x.end()); // Not sure what is inserted in the set
std::cout << y.size() << std::endl;

return 0;
}

Answer

When run, x contains in order:

2 4 7 11 12 14 17

y contains in order:

11 2 4 7

My hunch is that the set reverses the operator to check for equality (since a set only contains unique values). Thus only unique values of a%10 exist.

Comments