Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Even though I inserted 20 (distinct) elements into my std::set, it only has a size of 14?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading