Using std::set is the right thing to do.
All you need to do is provide a comparison operator< for the Points, so that it can figure out how to sort them, and which are equal.
(a < b == false && b < a == false) means a == b
Anyway.
1 2 3 4 5 6 7 8 9 10 11 12 13
class Point {
// ...
public:
// possible code
booloperator < (const Point &p) const
{
if (x == p.x)
return y < p.y;
return x < p.x;
}
};
Hey catfish2, thanks for your reply. How would I be able to use the setters/getters if I am using set? I am using vectors because of this.
I don't think std::set lets you modify objects after they're inserted. (For the reason that if you could do that, you'd mess up the order.)
So you can kiss your setters goodbye, but the getters will still work.
To iterate and display an std::set the old fashioned way, use:
1 2
for (std::set<Point>::const_iterator ci = mySet.begin(); ci != mySet.end(); ++ci)
std::cout << *ci << std::endl; // an iterator is a bit like a pointer
The new C++11 way (your compiler may not support this):
1 2
for (const Point &p: mySet) // range-based for loop
std::cout << p << std::endl;
Catfish2, is this the right way if I add one more int Z value in protected?
Not exactly. The purpose of a good operator< is to approximate Point1 < Point2 as well as possible.
So if you have x, y, z, it should look more like:
1 2 3 4 5 6 7 8 9 10 11 12
booloperator < (const Point &p) const
{
if (x == p.x)
{
if (y == p.y)
return z < p.z;
return y < p.y; // you miss this possibility
}
return x < px;
}
My iterators are fine now. Getting all the points of x,y i need. Amazing I did it that way (adding z in ) and everything came out fine lol.
How about sorting in a set then ? I need ascending / descending.
Lets say it will consider X first. and Ascending. So 1, 2, 3, 4, 4.
This is all X. Then it is sorted in place. Afterwhich it will then compare in ascending order of Y. How do i do this?
My iterators are fine now. Getting all the points of x,y i need. Amazing I did it that way (adding z in ) and everything came out fine lol.
The anomaly caused by your original operator< will be visible when you try to add more Points with equal x and z members, but unequal y.
How about sorting in a set then ? I need ascending / descending.
The elements are sorted by using your operator<, in ascending order (but it is you who decides what makes a Point smaller than another).
So you don't sort manually, the std::set does it for you. But you can use rbegin() and rend() instead of begin() and end() to iterate from the last element to the first.
Point1::Point1(int xx, int yy, int zz) : Point(xx, yy)
{
setDistFrOrigin();
}
// should be
Point1::Point1(int xx, int yy, int zz) : Point(xx, yy), z(zz)
{
setDistFrOrigin();
}
Also your ostream & operator << () function doesn't display the p1.z.