I have written a string comparison function. It works like I intended but I want a critic review. Took me a while to arrive at this so I'd like to know other ways that this could be done without STL support (like std::compare).
> I'd like to know other ways that this could be done without STL support
Here's one other way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int compare( const std::string& a, const std::string& b )
{
std::size_t index = 0 ;
const std::size_t min_sz = a.size() < b.size() ? a.size() : b.size() ;
// get to the position of the first mismatched character (up to a max of min_sz)
while( a[index] == b[index] && index < min_sz ) ++index ;
// if mismatch occurred before min_sz (before the end of either string)
if( index < min_sz ) return a[index] < b[index] ? -1 : +1 ;
// all characters up to min_sz were matched
if( a.size() == b.size() ) return 0 ; // if the strings are of equal length, they compare equal
elsereturn a.size() < b.size() ? -1 : +1 ; // otherwise, the shorter string is the smaller one
}