Using Constructors and Comparators in C |
Constructors in C++.
struct point {
int x, y;
point() {} // default constructor
point (int _x, int _y) {
x = _x;
y = _y;
}
};
Note that in C++, You do not need to use typedef as it is already typedefed to point, So you do need to use typedef for that.
Another way
struct point {
int x, y;
point() {} // default constructor
point (int x, int y): x(x), y(y) {}
};
comparators in C++
struct point {
int x, y;
point() {}
point (int x, int y) : x(x), y(y) {}
// overloading of < operator
bool operator<(const point &rhs) const{
// your main logic for the comparator goes here
return make_pair(y,x) < make_pair(rhs.y, rhs.x);
}
};
For more information about using operator overloading you can visit this link
Final Code:
// Comment
struct point {
int x, y;
point() {}
point (int _x, int _y) {
x = _x;
y = _y;
}
bool operator<(const point &rhs) const{
return make_pair(y,x) < make_pair(rhs.y, rhs.x);
}
bool operator==(const point &rhs) const{
return make_pair(y,x) == make_pair(rhs.y, rhs.x);
}
};
Sample uses:
Sorting an array in reverse order
Method 1:
vector a; sort(a.rbegin(), a.rend());
Method 2:
//For an vector
bool cmp(int a,int b) {
return a <= b;
}
int main() {
int n;
cin >> n;
vector a;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back(x);
}
sort (a.begin(), a.end(), cmp);
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
return 0;
}
For an array now.
bool cmp(int a,int b) {
return a <= b;
}
int a[100];
int main() {
int n;
cin &>> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort (a, a + n, cmp);
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
return 0;
}
Another Sample Problem
Deleting redundant points out of n points given. Two points are considered to be equal if both their x and y coordinates are equal.
struct point {
int x, y;
point() {}
point (int x, int y) : x(x), y(y) {}
bool operator<(const point &rhs) const{
return make_pair(y,x) < make_pair(rhs.y, rhs.x);
}
bool operator==(const point &rhs) const{
return make_pair(y,x) == make_pair(rhs.y, rhs.x);
}
};
int main() {
int n;
cin >> n;
vector a;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
a.push_back(point(x, y));
}
set st;
for (int i = 0; i < n; i++) {
st.insert(a[i]);
}
vector res;
set :: iterator it;
for (it = st.begin(); it != st.end(); it++) {
res.push_back(*it);
}
for (int i = 0; i < res.size(); i++)
cout <<; res[i].x <<" " << res[i].y << endl;
return 0;
}
Structs are the C way to emulate emulate real world objects whereas constructors, classes and objects are the full fledged C++ approach to object oriented programming. Inheritance, overloading, polymorphism, constructors, destructors are the key aspects of OOP in C++.