5.3.4 Sets of Struct Values
As mentioned before, a set contains unique values and if two values are equivalent, an insert statement ignores the second value.
It is easy to see if two numbers are the same, but what if you have a struct. How can you tell if two struct objects are the same?
The short answer is that C++ cannot do this on its own, and if it can’t do this on its own, you cannot use the struct in a set.
You can however tell C++ how to tell if objects are the same and once you do this, the struct can be used in a set.
Operator Overload
One of the more unique features of C++ is that you can overload an operator just like you overload other functions.
While this course is not going to go in-depth on operator overload, you can see the basic syntax below to overload the less than (<
) operator:
Notice that there are a few keywords here. The expression starts with bool operator
then the operator you want to overload. Inside the parenthesis, you list the other element you are going to compare to as the parameter (as a pass by reference). This is followed by the keyword const
and then the code block.
In the code block, you put the logic to determine which value is less than the other.
This might make more sense in an example.
Example
Take a look at an example where we have a rectangle
struct as defined below.
To determine which rectangles are greater than others, you can use the area of the rectangle. The operator overload function will look like this:
This function is actually placed inside the struct definition. With this in mind, the complete rectangle
struct will look like this:
Closing Note
In the example above, it is entirely possible for two rectangles to have the same area, but be very different. For example, a 20 by 5 rectangle has the same area as a 10 by 10 rectangle. Based on the definition you used above, the second rectangle would not be added because C++ would assume it is the same.
Keep this in mind as you decide on the criteria you use to determine the order. Instead of area, you could use another criterion to determine the order, such as size which would have given slightly different results.
Last updated