typedef vector<int> vec;
struct classcomp {
bool operator() (const vec& vec1, const vec& vec2) const{
if (vec1[0] > vec2[0]){
return true;
}
return false;
}
};
int main() {
set<vec,classcomp> v;
for (int i = 0; i < 20; i++){
v.insert({rand()%20,i});
}
cout << "size: " << v.size() << endl;
for (auto e : v){
cout << e[0] << " " << e[1] << endl;
}
}
In the above C++ code, I have defined a custom comparator and a ordered set of vectors which is sorted based on the first entry of the vector. I understand that the set does not store duplicates, but I inserted 20 distinct vectors (the second entry is unique for each vector), yet my set only has a size of 14. Why is this?
>Solution :
std::set does not use operator == to distinguish duplicate values. Instead, it uses Compare template argument to both order elements and tell when they are equivalent. The formal requirements for this argument can be found here: Compare, but the important one is this one:
if
!comp(a, b) && !comp(b, a)
then a and b are considered equivalent and insert operation fails.
Since your comparator only checks for value of first element of the vector, then any insert that tries to add another vector with identical first element will fail.