std::sort
and std::unique
both need to compare items to do their jobs. They have somewhat different requirements though: std::unique
compares for equality and std::sort
compares for ordering. One obvious possibility for your case would be code on this general order:
bool operator==(Vertex const &other) const {
return num == other.num;
}
bool operator<(Vertex const &other) const {
return num < other.num;
}
[Note: these would be member functions of your Vertex
class.]
It's possible to implement the required functionality in other ways, especially if (for example) you might want to sort objects based on one field sometimes, and by another field at other times (e.g., sort by number and sort by name, in the case of your Vertex class).
You can do that by passing a third parameter to sort
and/or unique
to tell it what to use to do the comparison. At least in current C++, if I'm going to do this, I generally use a lambda expression to specify the comparison:
std::sort(v.begin(), v.end(),
[](Vertex const &a, Vertex const &b) { return a.name < b.name; });
This puts the comparison code right next to the sort, so it's easy to see how you're doing the sorting. You can use a separate function or function object instead, but doing so means you need to be careful with the name to ensure it describes the sort order:
struct by_name {
bool operator()(Vertex const &a, Vertex const &b) const {
return a.name < b.name;
}
};
// ...
std:sort(v.begin(), v.end(), by_name());