As already mentioned the thing to remember is that the comparator should return true if and only if the first argument should be ordered before the second argument. If the comparator returns false both when the arguments are passed as (v1, v2) and as (v2, v1) it considers v1 and v2 to be equal. This is similar to how < (less than) works with numbers. If !(a < b) && !(b < a) then a must be equal to b. It is very important that the comparator gives a strict order. You should not have that v1 before v2, v2 before v3 and v3 before v1. That is not a good order and will screw things up.
The code posted by aquaz will not work. If the vectors are v1={1, 2} and v2={2, 1} then the comparator will return true despite the order of the v1, v2. v1 should be before v2 and v2 should be before v1. That doesn't make sense. Another problem is that it only works when the size of the two vectors are the same.
This comparator should work better:
1 2 3 4 5 6 7 8 9 10 11 12
|
struct cmp {
bool operator() (const vector<int> &v1,const vector<int> &v2) {
if (v1.size() != v2.size())
return v1.size() < v2.size();
for(size_t i=0;i<v1.size();i++){
if(v1[i] != v2[i]) {
return v1[i] < v2[i];
}
}
return false;
}
};
|
Sometimes you care about the order of the elements in the set. Sometimes useful if you prefer a certain order when iterating over the elements in the set. The above comparator will order small vectors before large vectors. If they have the same size it will order them by the first element that that is not equal in the two vectors.
If you instead want to order them in some other order you can simply change the comparator to get the order you want. This comparator will order the vectors a bit different and I think this is how the default comparator orders them.
1 2 3 4 5 6 7 8 9 10 11
|
struct cmp {
bool operator() (const vector<int> &v1,const vector<int> &v2) {
size_t minSize = min(v1.size(), v2.size());
for(size_t i=0;i<minSize;i++){
if(v1[i] != v2[i]) {
return v1[i] < v2[i];
}
}
return v1.size() < v2.size();
}
};
|