Make your own type work with < and ==, just like a number does.
What to build
A Version class with operator< and operator==, used to compare pairs of version numbers.
Requirements
- Store the major and minor numbers as private members.
- Write
operator<andoperator==as const member functions. - Use only those operators to decide whether the first version is older, newer or the same.
Input
The first line has q. Each of the next q lines has two versions such as 1.2 1.10.
Output
One line per pair: older, newer or same, describing the first version.
Constraints
1 ≤ q ≤ 100, and each number is from 0 to 1000.
Example
Input:
3
1.2 1.10
2.0 1.9
3.4 3.4
Output:
older
newer
same
Why it works
Version 1.10 is newer than 1.2 because 10 is greater than 2, which is why the parts are compared as numbers rather than as decimals or text. Once < and == are defined, the rest of the program reads naturally.
Examples
3 1.2 1.10 2.0 1.9 3.4 3.4
older newer same
1 0.1 0.0
newer
Hints
Hint 1
Read a version as an int, a char for the dot, and another int: `cin >> major >> dot >> minor`.
Hint 2
`operator<` compares the major numbers first, and the minor numbers only when the majors are equal.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
class Version {
int major, minor;
public:
Version(int a, int b) : major(a), minor(b) {}
bool operator<(const Version& o) const {
if (major != o.major) return major < o.major;
return minor < o.minor;
}
bool operator==(const Version& o) const {
return major == o.major && minor == o.minor;
}
};
int main() {
int q;
cin >> q;
while (q-- > 0) {
int a, b, c, d;
char dot;
cin >> a >> dot >> b >> c >> dot >> d;
Version x(a, b), y(c, d);
if (x == y) cout << "same" << endl;
else if (x < y) cout << "older" << endl;
else cout << "newer" << endl;
}
return 0;
}