While reading Scott Meyers "Effective STL", I decided to try out the case insensitive string compare in Item 35. I can't seem to get the lexicographical_compare() version to work right even though it's identical to the book. Here's my code:
I'm using Visual C++ 6.0, and I even tried using STL Port instead of the default VC 6.0 STL and got the same result.
Any ideas?
Code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
char
ToLower( char c )
{
if ( (c >= 'A') && (c <= 'Z') )
{
return c + 32;
}
return c;
}
bool
LessNoCase( char c1, char c2 )
{
// return (_tolower( static_cast<int>( c1 ) ) <
// _tolower( static_cast<int>( c2 ) ));
char c3 = ToLower( c1 );
char c4 = ToLower( c2 );
return (c3 < c4);
}
bool
CompareNoCase( const string& first,
const string& second )
{
// return (stricmp( first.c_str(), second.c_str() ) == 0);
return lexicographical_compare( first.begin(), first.end(),
second.begin(), second.end(),
LessNoCase );
}
int main()
{
string lower( "chris" );
string upper( "CHRIS" );
string mixed( "ChRiS" );
string other( "Hello" );
if ( CompareNoCase( lower, upper ) == false )
{
cout << "1. lower and upper don't match!" << endl;
}
if ( CompareNoCase( upper, mixed ) == false )
{
cout << "2. upper and mixed don't match!" << endl;
}
if ( CompareNoCase( mixed, other ) == true )
{
cout << "3. mixed and other mated!" << endl;
}
cout << endl << "DONE" << endl;
return 0;
}
Any ideas?