Rolling my own memicmp()

K

KPB

I'm currently reading Herb Sutter's Exceptional C++ book, specifically
the two items pertaining to the case insensitive string.

Basically, he achieves this by deriving from the std::char_traits<char>
class and inserting it into basic_string<>.

In one of the char_traits<> functions he implements (compare()), he
calls a function called memicmp(char const*, char const*, size_t);

I decided to roll my own based on the stdC++ libs, specifically
std::mismatch() and std::pair.

It seems to work based on my whole 5 minutes of testing.

Assuming that the function works correctly, I'm looking to see if anyone
can come up with a more elegant solution. For example, did I have to
actually create a functor (see ci_equal_to) or could I have performed
some binding operation?

Thanks,
KPB


--- BEGIN CODE ---

#include <iostream>
#include <utility>
#include <functional>
#include <cctype>
#include <string>
#include <cassert>

// My own version of memicmp that Herb Sutter uses
// in Exceptional C++
int memIcmp(char const* p1, char const* p2, size_t n);

int main()
{
using namespace std;

string s1 = "deTroit";
string s2 = "DetRoiT";

// current implementation of memIcmp
// assumes that both strings are exactly
// the same size.
assert(s1.size() == s2.size());

// memIcmp test
int i = memIcmp(s1.c_str(), s2.c_str(), s1.size());

// print result of string comparison
if(0 == i)
{
cout << "strings match" << endl;
}
else
{
cout << "strings do not match" << endl;
}

return 0;
}

// Should I have just derived this class from
// binary_function instead of equal_to?
struct ci_equal_to : public std::equal_to<char>
{
bool operator () (char left, char right)
{
return toupper(left) == toupper(right);
}
};

// Assumption: assume that both p1 and p2 are of size n
int memIcmp(char const* p1, char const* p2, size_t n)
{
using namespace std;

typedef pair<char const*, char const*> ci_diff_pair;
ci_diff_pair p = mismatch(p1, p1 + n, p2, ci_equal_to());

// both characters match exactly (case insensitive)
if (p.first == p1 + n && p.second == p2 + n)
{
return 0;
}

return *(p.first) < *(p.second) ? -1 : 1;
}

--- END CODE ---
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top