Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the STL set equality operator check size first?

When I'm using the == or != operator to compare two sets, does that operator actually compare the size of the two sets first? I'm wondering if I need to manually compare the two sizes first to make it more efficient, or if I would actually be making it less efficient. I know the equality and inequality operators will check size, I just don't know if it will do so first.

bool checkEqualTo( const set<int> & set1, const set<int> & set2 )
{
    // Should I include comparison of sizes first?
    if ( set1.size() != set2.size() )
    {
       return false;
    }
    if ( set1 != set2 )
    { 
        return false;
    }
    return true;
}
like image 745
Chance Avatar asked Oct 12 '25 09:10

Chance


1 Answers

Yes, that's the first thing that's checked — from the C++11 standard, §23.2.1 table 96 (Container requirements):

Expression:

     a == b (where a and b denote values of type X and X denotes a container class containing objects of type T)

Operational semantics:

   distance(a.begin(), a.end()) == distance(b.begin(), b.end()) &&
     equal(a.begin(), a.end(), b.begin())
like image 107
ildjarn Avatar answered Oct 14 '25 23:10

ildjarn