I want stl-set to sort element 0 of vector,look the code:
struct cmp{
bool operator()(vector<int> const &a, vector<int> const &b)const{
return a[0] < b[0];
}
};
int main(){
set<vector<int>, cmp> S;
vector<int> a = {0, 2};
vector<int> b = {1, 2};
vector<int> c = {1, 3};
S.insert(a);
S.insert(b);
S.insert(c);
cout << S.size() << endl;
getchar();
}
I get S.size() is 2, but obviously b and c is different. Is my cmp function written wrong, how should I write it? I would be very grateful if my question could be answered.
CodePudding user response:
C how does a STL set determine that two elements are equal?
It uses the comparison functor that you provide.
but obviously b and c is different.
No. According to the comparison functor that you provided, they aren't different.
Is my cmp function written wrong
It depends on what behaviour you want. If you want b and c to compare different, then it is written wrong.
how should I write it?
If your goal is for the elements to be equal only when they contain the same sequence, then you shouldn't write it at all. You can get that behaviour by using the default comparison functor:
std::set<std::vector<int>> S;
CodePudding user response:
I get S.size() is 2, but obviously b and c is different
The first elements in b
and c
are the same, hence with your comparator !(cmp(b,c) && !(cmp(c,b)
, ie neither of them compares less than the other and they are consisered equivalent.
Is my cmp function written wrong, how should I write it?
It depends. If you want to compare the first elements in the vectors then your comparator is right. If you want a different comparator then you should compare the vectors differently.
PS: Maybe you missed that the comparator is not only used to sort the elements in the set. It is also used to decide whether two elements are equivalent. Two elements are equivalent when !cmp(a,b) && !cmp(b,a)
. If two elements are equivalent, then the set will keep only one of them.